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

标签 python tkinter

我正在尝试创建一个图形用户界面,用户可以从可滚动列表中选择项目,但是一旦选择了复选按钮,我就无法打印出所选项目。当我运行以下代码时,最后打印出用户选择的内容的标签不会刷新。因此,如果用户改变主意,选择不同的水果,然后再次点击按钮,GUI 不会反射(reflect)这一点。

我的列表,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()

最佳答案

为了做你想做的事,我添加了另一个 list ,名为check_buttons ,保留tkinter每个的 ID tk.Checkbutton创建的。这使得以后可以清除每一个。

我还添加了另一个Frame保存所有水果名称的容器对象Label s。它是在 label_fruits() 中即时创建的第一次尝试通过调用 list_frame.destroy() 删除任何现有的之后。然后(重新)创建它并创建一组新的 Label s 被放入其中。

import tkinter as tk

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

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

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

checked_list = []
check_buttons = []  # Added.
fruit_vars = []

def cb_pressed():
    """ Checkbutton callback. """

    # (Re)create [the entire] list of checked fruits.
    checked_list.clear()
    for i, int_var in enumerate(fruit_vars):
       if int_var.get():  # Not zero -> checked.
            checked_list.append(mylist[i])


# Create scrollable Checkbuttons 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=tk.RIGHT, fill=tk.Y)
text.pack(side=tk.LEFT, fill=tk.BOTH, expand=tk.YES)

# Create IntVars and check_buttons list.
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_pressed)
    check_buttons.append(cb)
    text.window_create(tk.END, window=cb)
    text.insert(tk.END, "\n")


def label_fruits():
    """ Display the fruits user has checked. """

    global list_frame

    print(checked_list)

    try:
        list_frame.destroy()
    except NameError:  # Nonexistent.
        pass
    list_frame = tk.Frame(root)  # (Re)create Label container.
    list_frame.pack()
    for fruit in checked_list:
        tk.Label(list_frame, text=fruit).pack()

    # Clear out GUI by unchecking all the Checkbuttons.
    for cb in check_buttons:
        cb.deselect()


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

root.mainloop()

关于python - Tkinter GUI 重叠或刷新列表中的标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54101561/

相关文章:

python - 在 +/- 2 个工作日的日期切片 pandas 时间序列

python - 数据集中的评分一致性

标签自动调整大小的 Python PIL 图像

python - 标签中的图像未出现在辅助窗口中(tkinter)

python - 在开发与生产之间分离 Django 安装的应用程序

Python:将函数输出关联到字符串,然后组合成字典

python - 自定义 GUI 元素的类未显示

python - 如何在执行我们通过 pyinstaller 生成的可执行文件时隐藏黑屏?

python - 用于调用 TKinter GUI 的单元测试

python - 任务队列从 View 中工作,但从单元测试运行时出现 UnknownQueueError