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

Time:08-14

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!

CodePudding user response:

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.

CodePudding user response:

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

CodePudding user response:

I don't know a lot about Tkinter, but cant you do something like

if button != clicked:
   draw_button()
else:
   no_button

(its called pseudo code dont put it in your program lol.) If your game or whatever is in a loop, just include it in your loop.

clicked = None
while not clicked:
   button.draw()
   if button Is clicked:
      clicked = True
      continue
  • Related