3

I need to delete a widget, example:

    button1 = Button(root, text="start", command=self.cc).pack()

How do I make another widget which has the command to delete button1? or even just a function which when called, deletes button1.

I couldnt find the answer any where :/

there is another similar question (How to delete Tkinter widgets from a window?) BUT its 8 years old so the solutions may be outdated

coder_not_found
  • 202
  • 2
  • 13
  • i tried some things in it but it doesnt work for me (maybe beacuse its 8 years old, so there could be outdated solution) im running python3 whereas it might differ in that – coder_not_found Feb 21 '21 at 04:06
  • What did you try then? The suggested duplicate looks pretty solid to me. – Silvio Mayolo Feb 21 '21 at 04:07
  • 2
    It is all because you called the geometry manager in the same line which returns none. See this [answer](https://stackoverflow.com/a/1101765/10364425) for clarity. – Saad Feb 21 '21 at 04:10
  • i tried pack_forget and grid_forget both return an error: NoneType Object has no attribute to pack_forget/grid_forget: (it returns a NoneType Object) – coder_not_found Feb 21 '21 at 04:12
  • update: it still returns a none type error even after I removed the geometry function. I only used pack() in the entire class and no other geometry funtions – coder_not_found Feb 21 '21 at 04:17
  • The method is `destroy`. The reason it doesn't work is because of this: http://stackoverflow.com/q/1101750/7432. Tkinter hasn't changed significantly in the past 8 years. – Bryan Oakley Feb 21 '21 at 04:26

1 Answers1

2

Every widget has a function called destroy() and you can call it from another button-command, like this:

import tkinter as tk 


root = tk.Tk()

button = tk.Button(root,text="Btn1")
button.grid(row=0,column=0)
button2 = tk.Button(root,text="Delete",command=button.destroy)
button2.grid(row=1,column=0)
    
root.mainloop()

If you want to destroy all widgets inside a frame or "root", you can use a function called winfo_children which selects all children widgets and then with a loop destroy each of them:

def destroyall():
    for widget in root.winfo_children():
            widget.destroy()

button3 = tk.Button(root,text="Delete All",command=destroyall)
button3.grid(row=2,column=0)