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

因此,目前我创建了一个按钮,能够按预期链接到此列表中的指定站点(硬编码)。


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 webbrowser

from tkinter import *



# SETUP WINDOW ELEMENTS

win = Tk()

win.title("Setting Up GUI")

win.geometry("500x500")


# List elements

Titles = ["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 widgets

option_select = dict()


# create a variable class to be manipulated by Radio buttons

ttl_var = StringVar(value=" ")


# Fill radiobutton dictionary with keys from game list with Radiobutton

# values assigned to corresponding title name

for 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 link

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])) 


win.mainloop()

我想知道是否有办法将此callback功能以某种方式合并到for title in Options:...单选按钮代码行中。


慕标5832272
浏览 99回答 1
1回答

扬帆大鱼

您可以简单地使用 aIntVar代替 a StringVar,然后使用该值urls在 中建立索引callback:...ttl_var = IntVar(value=0)for num, title in enumerate(Titles[:-1]):&nbsp; &nbsp; option_select[title] = Radiobutton(win, variable=ttl_var, text=title,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;value=num, justify=LEFT)&nbsp; &nbsp; option_select[title].pack(fill='both')def callback(event=None):&nbsp; &nbsp; 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)...
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python