如何在Tkinter中动态删除复选框? [英] How to delete checkboxes dynamically in tkinter?
问题描述
我正在使用 tkinter
制作一种待办事项应用程序.为此,我想动态生成复选框,并且已经使用函数成功完成了此操作,但是当用户按下清除按钮时,我也想删除这些复选框.该怎么做.
I am making a sort of todo app using tkinter
. For this I want to generate checkbox dynamically and I have successfully done this using a function but I also want to delete those checkboxes when user press clear button. How can this be done.
name=Stringvar()
ent=Entry(root,textvariable=name).pack()
def clear(ent):
ent.pack_forget()
def generate():
k=name.get()
c=Checkbutton(root,text=k)
c.pack()
btn1=Button(root,text="Submit",command=generate)
btn1.pack()
btn2=Button(root,text="Clear",command=clear)
btn2.pack()
我想删除该复选框,但由于功能清除不读取 c.pack_forget()
I want to delete the checkbox but I cannot do so as function clear does not read c.pack_forget()
推荐答案
只存储在 generate()
中创建的 Checkbutton
的所有对象非常简单像这样
It is very simple to do just store all the objects of Checkbutton
created in the generate()
function like so
-
首先,您需要一个
List
.
提示:如果需要存储有关该对象的更多信息,请使用字典".
附加创建的每个 Checkbutton
.( List.append(c)..
)
然后在 for
循环的帮助下,从 List
中的 pack_forget()
Checkbutton
.如果您不打算将来使用那些检查"按钮,则使用 destroy()
而不是 pack_forget()
.
Then pack_forget()
the Checkbutton
from the List
with the help of for
loop. If you are not planning to use those Check buttons in future then use destroy()
instead of pack_forget()
.
这是代码:
from tkinter import *
root = Tk()
name = StringVar()
check_box_list = []
ent=Entry(root,textvariable=name).pack()
def clear():
for i in check_box_list:
i.pack_forget() # forget checkbutton
# i.destroy() # use destroy if you dont need those checkbuttons in future
def generate():
k=name.get()
c=Checkbutton(root,text=k)
c.pack()
check_box_list.append(c) # add checkbutton
btn1=Button(root,text="Submit",command=generate)
btn1.pack()
btn2=Button(root,text="Clear",command=clear)
btn2.pack()
mainloop()
如果要分别删除每个而不是全部清除,请尝试此操作.
If you want to remove each one separately instead of clear all then try this.
from tkinter import *
root = Tk()
name = StringVar()
check_box_list = []
ent=Entry(root,textvariable=name).pack()
def clear():
for i in check_box_list:
if i.winfo_exists(): # Checks if the widget exists or not
i.pack_forget() # forget checkbutton
# i.destroy() # use destroy if you dont need those checkbuttons in future
def generate():
k=name.get()
f = Frame(root)
Checkbutton(f, var=StringVar(), text=k).pack(side='left')
Button(f, text='✕', command=f.destroy).pack(side='left')
check_box_list.append(f) # add Frame
f.pack()
btn1=Button(root,text="Submit",command=generate)
btn1.pack()
btn2=Button(root,text="Clear All",command=clear)
btn2.pack()
mainloop()
这篇关于如何在Tkinter中动态删除复选框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!