Tkinter GUI重叠或刷新列表中的标签

时间:2019-01-09 00:12:04

标签: python tkinter

我正在尝试创建一个gui,用户可以在其中从滚动列表中选择项目,但是一旦选中了选择按钮,我就无法打印出所选择的项目。当我运行以下代码时,我最后打印出用户所选内容的标签不会刷新。因此,如果用户改变主意,采摘不同的水果,然后再次按下按钮,则gui不会反映出来。

我的列表check_list进行了适当的更改,但是我基本上需要一种清除GUI并再次标记的方法。我觉得一种简单的方法是忘记框架(即frame.pack_forget()),但到目前为止我还没有运气。

import tkinter as tk
from tkinter import *

mylist = ['apple','pear','kiwi','banana','strawberry','pineapple']

root = Tk()
root.geometry('400x100')

frame = Frame(root)
frame.pack(fill=BOTH, expand = True)

fruit_vars = []
check_list= []

def cb_checked():
    global check_list
    for ctr, int_var in enumerate(fruit_vars):
           if int_var.get():     ## IntVar not zero==checked
                temp = mylist[ctr]
                check_list.append(temp)

    #Keep only the unique fruits in list
    check_list_set = set(check_list)
    check_list = list(check_list_set)
    return check_list


#Create scrollable checkboxes of fruit options
text = tk.Text(root, cursor="arrow", width = 5, height = 5)
vsb = tk.Scrollbar(root, command=text.yview)
text.configure(yscrollcommand=vsb.set)
vsb.pack(side="right", fill="y")
text.pack(side="left", fill="both", expand=True)

for fruit in mylist:
    fruit_vars.append(tk.IntVar())
    cb = tk.Checkbutton(text, text=fruit, variable=fruit_vars[-1],
                        onvalue=1, offvalue=0, command=cb_checked)
    text.window_create("end", window=cb)
    text.insert("end", "\n")


#Print which fruits the user chose to the gui
def label_fruits():
    print(check_list)
    for fruits in check_list:
        Label(root, text=fruits).pack()

Button(root, text='Show Chosen Fruits', command=label_fruits).pack()

root.mainloop()

1 个答案:

答案 0 :(得分:2)

要执行所需的操作,我添加了另一个名为list的{​​{1}},以保留每个创建的check_buttons的{​​{1}} id。这样一来,每个人都可以稍后清除。

我还添加了另一个tkinter容器对象来容纳所有水果名称tk.Checkbutton。它是在尝试通过调用Frame来摆脱任何现有变量之后,在Label中即时创建的。然后(重新)创建它,并放入一组新的label_fruits()

list_frame.destroy()
相关问题