簡體   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