简体   繁体   English

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

[英]Combining radio buttons with different functions together

So I've created two sets of 3 radio buttons.所以我创建了两组 3 个单选按钮。 The first set display contents of a list to a display box.首先将列表的显示内容设置为显示框。 While the other set of radio buttons redirect you to a set amount of sites.而另一组单选按钮将您重定向到一定数量的站点。 I'm trying to combine the the redirect functionality of the second set to the first.我正在尝试将第二组的重定向功能与第一组结合起来。 This picture shows how it currently functions.这张图片显示了它目前的运作方式。

Below is the simplified version of my main code:以下是我的主要代码的简化版本:

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

I tried indenting the second for loop into the first loop but that just ended up making more redundant radio buttons.我尝试将第二个for loop缩进到第一个循环中,但这最终导致了更多冗余的单选按钮。 I've just been stumped and couldn't find any other solutions online that related to my issue.我刚刚被难住了,无法在网上找到与我的问题相关的任何其他解决方案。

I would use the 'command' options that most tk objects have.我会使用大多数 tk 对象具有的“命令”选项。 Do something like this:做这样的事情:

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

That will make three radio buttons with the for-loop (I just simplified the names; you can call them whatever,) and a button.这将制作三个带有 for 循环的单选按钮(我只是简化了名称;您可以随意称呼它们)和一个按钮。 Then you should include two functions:那么你应该包括两个函数:

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

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

when the button is clicked, its command is callback so it's going to do that when you click it当按钮被点击时,它的命令是callback所以当你点击它时它会这样做
when a radio is clicked, its command is changedRadio so it will run that function when you click them当一个收音机被点击时,它的命令是changedRadio所以当你点击它们时它会运行那个功能

that should do what you are looking for except that webbrowser line is wrong urls[ttl_var.get()] in particular这应该做你正在寻找的东西,除了 webbrowser 行是错误的urls[ttl_var.get()]
ttl_var.get() is going to give you a string which cannot be used to index something in urls While you could have it find which index in your options list that is, maybe it's just best to rearrange a few things ttl_var.get()将给你一个字符串,它不能用来索引urls某些东西虽然你可以让它在你的选项列表中找到哪个索引,但也许最好重新排列一些东西

here is my suggested structure:这是我建议的结构:

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

Cheers干杯

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

相关问题 Python Pandas:有效地汇总不同列上的不同函数并将结果列组合在一起 - Python Pandas: efficiently aggregating different functions on different columns and combining the resulting columns together 将不同的功能组合成一个Python - Combining different functions into One , Python 你能把不同的字符串函数组合在一起吗? - Can you combine different string functions together? 如何将具有不同数量参数的函数组合在一起 - how to group together functions with different number of parameters Kivy - 结合两种不同的浮动布局并对齐浮动按钮 - Kivy - Combining two different float layouts and aligning the float buttons 结合2个功能 - Combining 2 functions tkinter 在选择不同的单选选项时会创建额外的按钮 - tkinter is creating extra buttons when selecting different radio options Kivy 分组复选框(单选按钮)全部点击在一起,并从屏幕上的任何位置? - Kivy grouped checkboxes (radio buttons) all clicking together, and from anywhere on the screen? 将许多正则表达式操作组合在一起 - Combining Many Regex Operations Together 如何根据在特定页面上按下的下一步按钮调用不同的功能 - How to call different functions based on next buttons pressed on specific pages
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM