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

2024-10-03 04:31:20 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我创建了两组3个单选按钮。将列表的第一组显示内容设置为显示框。而另一组单选按钮则将您重定向到一定数量的站点。我正在尝试将第二个集合的重定向功能与第一个集合相结合。这个picture显示了它当前的功能

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

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缩进第一个循环,但结果是生成了更多冗余的单选按钮。我刚刚被难住了,在网上找不到任何与我的问题相关的解决方案


Tags: textfortitlevarwinlspackdp
1条回答
网友
1楼 · 发布于 2024-10-03 04:31:20

我将使用大多数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,因此当您单击收音机时,它将运行该功能

这应该做什么,你正在寻找除了网络浏览器线是错误的 urls[ttl_var.get()]尤其是
ttl_var.get()将给您一个字符串,该字符串不能用于索引{}中的某些内容,而您可以让它在选项列表中找到哪个索引,也就是说,也许最好重新排列一些内容

以下是我建议的结构:

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

干杯

相关问题 更多 >