Is it possible to destroy a button or checkbox when it is clicked?

Question:

I am currently using tkinter to build a GUI and one of the functionalities I was hoping to achieve with the buttons was if it can be destroyed when it is clicked. I tried something along the lines of:

button = Button(window, text="hello", command=button.destroy()

This doesn’t work as I’m getting the error:
UnboundLocalError: local variable 'button' referenced before assignment.

Are there are workarounds to accomplish a task like this?

Asked By: Patrick Rodriguez

||

Answers:

that depends.. there is the .grid_forget method (or .pack_forget using pack instead of grid) if you don’t want to delete permanently the widget (you can re-add it with .grid), and also the .grid_remove or pack.remove, but otherwise I suggest you to use .destroy()

Answered By: JacopoBiondi

You need to save a reference to the button, and then call the destroy method on the button. Here’s one way:

button = Button(window, text="hello")
button.configure(command=button.destroy)

The problem in your code is that you’re trying to use button before the button has been created. Creating the button and then configuring the button in a separate step works around that problem since button exists by the time the second line is called.

Also notice that command is set to button.destroy, not button.destroy(). With the parenthesis, you’re going to immediately call the method instead of assigning the command to the button.

Answered By: Bryan Oakley
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.