因此,目前我創建了一個按鈕,能夠按預期鏈接到此列表中的指定站點(硬編碼)。urls = ['https://steamcharts.com/top', 'https://spotifycharts.com/regional/global/weekly/latest', 'https://www.anime-planet.com/anime/top-anime/week' ]通過這段代碼:def callback(url): webbrowser.open_new(url)source_bttn = Button(win, text="Show Source", fg="blue", cursor="hand2")source_bttn.pack()source_bttn.bind("<Button-1>", lambda e: callback(urls[1])) 但是,我希望此按鈕使用戶訪問的站點依賴于單選按鈕的選擇。下面是我的主要代碼的簡化版本import webbrowserfrom tkinter import *# SETUP WINDOW ELEMENTSwin = Tk()win.title("Setting Up GUI")win.geometry("500x500")# List elementsTitles = ["Steam Top Games\n[Title and Current Player Count]", "Top Weekly Spotify Songs\n[Title and Artist]", "Trending Anime's Weekly\n[Title and Release Date]", "Steam Top Games\n[3 October 2020]" ]urls = ['https://steamcharts.com/top', 'https://spotifycharts.com/regional/global/weekly/latest', 'https://www.anime-planet.com/anime/top-anime/week' ]Options = [(Titles[0]), (Titles[1]), (Titles[2]), ]# Add RadioButtons + Labels to "Current #2" frame# Create an empty dictionary to fill with Radiobutton widgetsoption_select = dict()# create a variable class to be manipulated by Radio buttonsttl_var = StringVar(value=" ")# Fill radiobutton dictionary with keys from game list with Radiobutton# values assigned to corresponding title namefor title in Options: option_select[title] = Radiobutton(win, variable=ttl_var, text=title, value=title, justify=LEFT) # Display option_select[title].pack(fill='both')# Creating button linkdef callback(url): webbrowser.open_new(url)source_bttn = Button(win, text="Show Source", fg="blue", cursor="hand2")source_bttn.pack()source_bttn.bind("<Button-1>", lambda e: callback(urls[1])) win.mainloop()我想知道是否有辦法將此callback功能以某種方式合并到for title in Options:...單選按鈕代碼行中。
1 回答

揚帆大魚
TA貢獻1799條經驗 獲得超9個贊
您可以簡單地使用 aIntVar代替 a StringVar,然后使用該值urls在 中建立索引callback:
...
ttl_var = IntVar(value=0)
for num, title in enumerate(Titles[:-1]):
option_select[title] = Radiobutton(win, variable=ttl_var, text=title,
value=num, justify=LEFT)
option_select[title].pack(fill='both')
def callback(event=None):
webbrowser.open_new(urls[ttl_var.get()])
source_bttn = Button(win, text="Show Source", fg="blue", cursor="hand2")
source_bttn.pack()
source_bttn.bind("<Button-1>", callback)
...
添加回答
舉報
0/150
提交
取消