Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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? Any help would be great. Thank you!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading