繁体   English   中英

将具有不同功能的单选按钮组合在一起

[英]Combining radio buttons with different functions together

所以我创建了两组 3 个单选按钮。 首先将列表的显示内容设置为显示框。 而另一组单选按钮将您重定向到一定数量的站点。 我正在尝试将第二组的重定向功能与第一组结合起来。 这张图片显示了它目前的运作方式。

以下是我的主要代码的简化版本:

import webbrowser
from tkinter import *

# SETUP WINDOW ELEMENTS
win = Tk()
win.title("Setting Up GUI")
win.geometry("500x500")

# -----Listbox display for selected radio button ----------------------------------------------------------#
dp_bx = Listbox(win, bg='SeaGreen1')
dp_bx.config(width=0, height=5)
lbl = Label(dp_bx, text="", bg='SeaGreen1')
lbl.pack()

# 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'
        ]
Steam_ls = ("Cherry", "Tree ", "Perri ")
Anime_ls = ("Pear", "Fair ", "Care ")
Spotify_ls = ("Cat", "Mat ", "Bat ")


def callback(event=None):
    webbrowser.open_new(urls[ttl_var.get()])
def lbl_update(*args):
    selection = "2. "
    selection = selection + ttl_var.get()
    lbl['text'] = selection


Options = [(Steam_ls[1], Titles[0]),
           (Spotify_ls[1], Titles[1]),
           (Anime_ls[1], Titles[2]),
           ]

# 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=" ")
link_var = IntVar(value=0)

# -----Links Selected Radio Button to "Dp_bx" Widget --------=-----------------------------------------#
for option, title in Options:
    option_select[option] = Radiobutton(win, text=title, variable=ttl_var, value=option,
                                        bg='SeaGreen1', justify=LEFT)
    option_select[option].pack(fill='both')

# -----Links Radio Button to "Show Source" Widget --------=-----------------------------------------#
for num, title in enumerate(Titles[:-1]):
    option_select[title] = Radiobutton(win, variable=link_var, text=title,
                                       value=num, justify=LEFT, bg='SeaGreen1')
    option_select[title].pack(fill='both')

source_bttn = Button(win, text="Show Source", fg="blue", cursor="hand2")
source_bttn.pack()
source_bttn.bind("<Button-1>", callback)
# -----Listbox display for selected radio button ----------------------------------------------------------#
dp_bx = Listbox(win, bg='SeaGreen1')
dp_bx.config(width=0, height=5)
lbl = Label(dp_bx, text="", bg='SeaGreen1')
lbl.pack()

# ----- Run lbl_update function every time ttl_var's value changes ------------------------------------#
ttl_var.trace('w', lbl_update)
dp_bx.pack(side=LEFT, fill=BOTH)
win.mainloop()

我尝试将第二个for loop缩进到第一个循环中,但这最终导致了更多冗余的单选按钮。 我刚刚被难住了,无法在网上找到与我的问题相关的任何其他解决方案。

我会使用大多数 tk 对象具有的“命令”选项。 做这样的事情:

for i in ('first', 'second', 'third'):
    b = Radiobutton(win, text=i, varriable=ttl_var, value=option,
        command=changedRadio)
    b.pack(fill='both')
source_bttn = Button(win, text="Show Source", command=callback)
source_bttn.pack()

这将制作三个带有 for 循环的单选按钮(我只是简化了名称;您可以随意称呼它们)和一个按钮。 那么你应该包括两个函数:

def changedRadio():
    lbl['text'] = "2. " + ttl_var.get()
    or whatever you want this to do

def callback(*_):
    webbrowser.open_new(urls[ttl_var.get()])

当按钮被点击时,它的命令是callback所以当你点击它时它会这样做
当一个收音机被点击时,它的命令是changedRadio所以当你点击它们时它会运行那个功能

这应该做你正在寻找的东西,除了 webbrowser 行是错误的urls[ttl_var.get()]
ttl_var.get()将给你一个字符串,它不能用来索引urls某些东西虽然你可以让它在你的选项列表中找到哪个索引,但也许最好重新排列一些东西

这是我建议的结构:

import webbrowser
from tkinter import *

class MyLittleOrganizer:
    def __init__(self, title, url, ls):
        self.title = title
        self.url = url
        self.ls = ls

def changedRadio(*_):
    # I don't totally get what you're doing here
    # but you can get which option is picked from ttl_var
    # and then have it do whatever logic based on that
    picked_item = everything[ttl_var.get()]
    print(picked_item.title)
    print(picked_item.url)
    print(picked_item.ls)
    print()

def callback(*_):
    webbrowser.open_new(everything[ttl_var.get()].url)

    win = Tk()
win.title("Setting Up GUI")
win.geometry("500x500")

dp_bx = Listbox(win, bg='SeaGreen1')
dp_bx.config(width=0, height=5)
lbl = Label(dp_bx, text="", bg='SeaGreen1')
lbl.pack()

everything = []
everything.append( MyLittleOrganizer(
    "Steam Top Games",
    'https://steamcharts.com/top',
    ("Cherry", "Tree ", "Perri ")) )
everything.append( MyLittleOrganizer(
    "Top Weekly Spotify Songs",
    'https://spotifycharts.com/regional/global/weekly/latest',
    ("Pear", "Fair ", "Care ")) )
everything.append( MyLittleOrganizer(
    "Trending Anime's Weekly",
    'https://www.anime-planet.com/anime/top-anime/week',
    ("Cat", "Mat ", "Bat ")) )

ttl_var = IntVar(value=-1)

for index, entry in enumerate(everything):
    b = Radiobutton(win, text=entry.title, variable=ttl_var, value=index, command=changedRadio)
    b.pack(fill='both')
source_bttn = Button(win, text="Show Source", command=callback)
source_bttn.pack()

干杯

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM