It is very simple to do just store all the objects of Checkbutton
created in the generate()
function like so
First you need a List
.
Tip: Use Dictionary if you need to store more information about the object.
Append each Checkbutton
created. (List.append(c)..
)
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()
.
Here is the code:
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()