为了账号安全,请及时绑定邮箱和手机立即绑定

配置根据所选单选按钮链接到站点的按钮

配置根据所选单选按钮链接到站点的按钮

慕标5832272 2023-11-09 21:41:26
因此,目前我创建了一个按钮,能够按预期链接到此列表中的指定站点(硬编码)。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)


...


查看完整回答
反对 回复 2023-11-09
  • 1 回答
  • 0 关注
  • 97 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信