1

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()

I want to delete the checkbox but I cannot do so as function clear does not read c.pack_forget()

vezunchik
  • 3,669
  • 3
  • 16
  • 25
Kundan Jha
  • 104
  • 3
  • 11
  • You could try this answer: https://stackoverflow.com/a/12365098/8411228. If you don't want to call it directly you need a way, to pass arguments to the function. For this you could use lambdas: https://stackoverflow.com/a/6921225/8411228 – Uli Sotschok May 05 '19 at 07:42

1 Answers1

4

It is very simple to do just store all the objects of Checkbutton created in the generate() function like so

  1. First you need a List.

    Tip: Use Dictionary if you need to store more information about the object.

  2. Append each Checkbutton created. (List.append(c)..)

  3. 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()
Saad
  • 3,340
  • 2
  • 10
  • 32