【问题标题】:Python hyperlink inside a loop doesn't loop thought the different id`s of JSON data循环内的 Python 超链接不会循环认为 JSON 数据的不同 ID
【发布时间】:2020-03-21 22:40:14
【问题描述】:

我正在尝试使用来自 JSON 文件的超链接在 tkinter 循环中添加按钮。当我按下按钮时,所有按钮的超链接都保持不变。它不会通过带有 JSON id 的 URL 链接循环。

当我打印它们时,它们都是不同的。

from urllib.request import urlopen 
import json
import webbrowser
import tkinter as tk    

with urlopen("https:example") as response:
source = response.read()          

data=json.loads(source)


#this is the function that should be triggered with different url each time
def openweb():
   webbrowser.open(url,new=1)

count=0
for product in data:
   id = product['id']  
   name = product['name']  
   price = product['price']  
   aciklama = product['description']  

   #these are the links for the buttons
   url = "https://www.example.com/tr-tr/i/"+id  
   #and here are the buttons with the command openweb defined above
   element = tk.Button(canvasFrame, text='Button', borderwidth=0, bg="#EBEBEB",command=openweb)  
   element.grid(row=count,column=1,padx=5, pady=5, sticky="nsew")  
   T = tk.Text(canvasFrame, height=2, width=30)  
   T.insert(tk.INSERT,count)  
   T.grid(row=count,column=2,padx=5, pady=5)  
   count=count+1  

root.mainloop()

【问题讨论】:

  • 当您尝试打印时,它正在 for 循环内打印。但是每次您的 ID 在 URL 中被覆盖时,最后一个 ID 都会出现在最终 URL 中。我也看不到 URL 在 for 循环中的任何地方都被分配了
  • 是什么让您认为您的按钮会打印不同的东西?所有这些都有相同的确切命令。到仅在按下按钮时调用的外部函数。

标签: python for-loop url tkinter hyperlink


【解决方案1】:

您需要在按钮命令中使用lambda

这里的问题是,在您的循环中,您为每个循环分配/覆盖 URL,因此 URL 唯一可以是循环中的最后一个值。为了保持正确的值,让我们使用 lambda 将 URL 分配给 lambda 变量,以便将其保存在按钮命令中。

我们还需要更新您的函数以接受参数,以便我们可以传递该 URL。

试试这个更新的函数和循环,如果您有任何问题,请告诉我。

def openweb(url):
   webbrowser.open(url, new=1)

count = 0

for product in data:
   id = product['id']  
   name = product['name']  
   price = product['price']  
   aciklama = product['description']  
   url = "https://www.example.com/tr-tr/i/"+id  
   tk.Button(canvasFrame, text='Button', borderwidth=0, bg="#EBEBEB",
             command=lambda u=url: openweb(u)).grid(row=count, column=1, padx=5, pady=5, sticky="nsew")  
   txt = tk.Text(canvasFrame, height=2, width=30)  
   txt.insert(tk.INSERT, count)  
   txt.grid(row=count, column=2, padx=5, pady=5)  
   count += 1

【讨论】:

  • @abdussamed17 你从来没有真正使用 URL 中的任何东西来创建你的按钮。永远不会有任何时候按钮可以假设您想要的只是因为与按钮同时定义了一个值。你必须具体。这就是我们在这里使用lambda 的原因。它实际上在这样的循环中被大量使用,因为如果你不这样做会出现一个烦人的问题。如果我的回答对您有用,请确保选中复选标记以表明您的问题已得到回答。
  • Mike 非常感谢您提供的详细信息。
猜你喜欢
  • 2018-02-22
  • 2012-09-06
  • 2016-02-08
  • 2014-02-20
  • 2016-04-24
  • 2018-03-30
  • 1970-01-01
  • 1970-01-01
  • 2019-04-09
相关资源
最近更新 更多