简体   繁体   中英

Combining radio buttons with different functions together

So I've created two sets of 3 radio buttons. 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. 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. 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. 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
when a radio is clicked, its command is changedRadio so it will run that function when you click them

that should do what you are looking for except that webbrowser line is wrong urls[ttl_var.get()] in particular
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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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