簡體   English   中英

循環內的Python超鏈接不會認為JSON數據的ID不同

[英]Python hyperlink inside a loop doesn't loop thought the different id`s of JSON data

我正在嘗試使用來自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()

您將需要在按鈕命令中使用lambda

這里的問題是在循環中,您為每個循環分配/覆蓋URL,因此URL唯一可以是循環中的最后一個值。 為了保持正確的值,讓我們使用lambda將URL分配給lambda變量,以便將其保留在button命令中。

我們還需要更新您的函數以接受參數,以便我們可以傳遞該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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM