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!
>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.