Tkinter:列表框不从函数调用填充,从列表填充

问题描述 投票:0回答:1

我有一个创建列表的函数,另一个函数应该用该列表中的项目填充 tkinter 列表框。单击单选按钮时,列表框的内容应更新。

创建列表的函数 get_available_decks() 在命令行上按预期工作。但列表框并未从该列表中填充。

当我用 ['1', '2', '3'] 等测试列表替换对 get_available_decks 的调用时,列表框将按预期填充。

为什么列表框没有通过调用 get_available_decks 填充?

def get_available_decks(master_deck_list, deck_type_selection):
    # Assign the list of deck names to deck_list
    decks_list = []
    
    for av_deck in master_deck_list:
        if deck_type_selection == 'official':
            if av_deck['official'] == True:
                decks_list.append(av_deck['name'])
        elif deck_type_selection == 'community':
            if av_deck['official'] == False:
                decks_list.append(av_deck['name'])
        elif deck_type_selection == 'all':
            decks_list.append(av_deck['name'])

    # for i in decks_list:
    #     print(i)

    return decks_list

def update_decklist():
    av_box.delete(0, tk.END)
    decklist = get_available_decks(master_deck_list, deck_type_selection)
    for item in decklist:
        # item = tk.StringVar(item)
        av_box.insert(tk.END, item)

# Deck type radio buttons
radio_1 = tk.Radiobutton(decktypes_frame, text="Official", variable=deck_type_selection, value="official", command=lambda: update_decklist())
radio_1.grid(column=0, row=0, padx=5, pady=5)
radio_2 = tk.Radiobutton(decktypes_frame, text="Community", variable=deck_type_selection, value="community", command=lambda: update_decklist())
radio_2.grid(column=1, row=0, padx=5, pady=5)
radio_3 = tk.Radiobutton(decktypes_frame, text="All", variable=deck_type_selection, value="all", command=lambda: update_decklist())
radio_1.grid(column=0, row=0, padx=5, pady=5)
radio_3.grid(column=2, row=0, padx=5, pady=5)

# decksframe holds the available and selected decks lists
decksframe = tk.LabelFrame(main, text="Available Decks")
decksframe.columnconfigure(0, weight=3)
decksframe.columnconfigure(1, weight=3)

# Available Decks
av_box = tk.Listbox(decksframe, selectmode="multiple", exportselection=0)
av_box.grid(column=0, row=0, padx=5, pady=5)
python list tkinter listbox iteration
1个回答
0
投票

请注意,传递给

deck_type_selection
get_available_decks()
是 tkinter
StringVar
的实例,因此使用
get_available_decks()
内部的字符串检查它很可能会被评估为
False
,并且不会将任何内容附加到
decks_list
中。您应该改为传递该变量中的值:

def update_decklist():
    av_box.delete(0, tk.END)
    # use .get() to get the value of deck_type_selection
    decklist = get_available_decks(master_deck_list, deck_type_selection.get())
    for item in decklist:
        av_box.insert(tk.END, item)
© www.soinside.com 2019 - 2024. All rights reserved.