Tkinter-使用复选框删除多个记录

时间:2020-11-04 21:23:40

标签: python tkinter checkbox

我正在尝试填充结果列表(在此示例中为python列表),并为每个结果提供自己的Checkbutton。这与TK按钮代码中的variable=Variable()一起工作,尽管我不确定它是如何工作的。 生成结果时,我需要能够选择它们,然后将其删除。我正在寻求帮助以获取每个复选框的状态,因此我可以删除该条目。这是我到目前为止的代码。

from tkinter import *

root = Tk()
root.title("DB Sandbox")
root.geometry("400x400")

def del_selected():
    pass

results = ['one', 'two', 'three', 'four']

for result in results:
        l = Checkbutton(root, text=result, variable=Variable())
        l.pack()

delbutt = Button(root, text="Delete Selected", command=del_selected)
delbutt.pack(pady=10)


root.mainloop()

对此表示感谢!

1 个答案:

答案 0 :(得分:0)

正如评论中提到的@ acw1668一样,Checkbutton可能不是此任务的最佳选择,但如果您确实愿意,则需要跟踪每个复选框及其变量,就像这样:

from tkinter import *

root = Tk()
root.title("DB Sandbox")
root.geometry("400x400")

def del_selected():
    global check_buttons, butt_vars # the best approach would be OOP, but this works
    for button, var in zip(check_buttons, butt_vars):
        if var.get(): # button selected: var.get() == 1, otherwise: var.get() == 0
            button.forget() # remove it from the geometry manager

results = ['one', 'two', 'three', 'four']
# this holds the variables to check whether the checkbox is selected or not
butt_vars = [IntVar() for _ in range(len(results))]
# this holds the checkbutton instances
check_buttons = [Checkbutton(root, text=x, variable=butt_vars[i]) for i, x in enumerate(results)]

for butt in check_buttons:
        butt.pack()

delbutt = Button(root, text="Delete Selected", command=del_selected)
delbutt.pack(pady=10)


root.mainloop()
相关问题