Home > Back-end >  How to destroy a button widget that was placed in an if condition? Tkinter
How to destroy a button widget that was placed in an if condition? Tkinter

Time:04-21

I couldn't word my question well but here's some context.

I created a button in tkinter and I used .place(x, y) inside an if condition but now I want to destroy it if another condition is met. It doesn't get destroyed even if the second condition is met. Please help.

from tkinter import *

window = Tk()

button = Button(window, text='Button')

x = 10 
y = 10 # just imagine that y became 5 at some point

if x == 10:
    button.place(x=0, y=0)

elif y == 5:
    button.destroy() 

window.mainloop()

CodePudding user response:

I am not exactly sure what you want to accomplish here, but you seem to be misunderstanding how if-elif-else works. It is intended to give alternatives for the values of the same variable, or in any case, both possibilities shouldn't be possible to happen simultaneously to get the desired outcome. Elif is short for "else if", meaning that it's evaluated only if the "if" statement is false.

In your case, x is already equal to 10 and you aren't changing it at any point, so the "if" condition is always fulfilled and the code never gets to the "elif" statement.

If y is changing and reaches 5, you could change the "elif" statement into "if" and add the condition that y has to be not equal to 5 when creating the button (otherwise, it will constantly create and destroy itself).

Also, as your current code works, there is no loop running. The code evaluates only once.

If I understand what you want to do, it's something along these lines.

from tkinter import *
window = Tk()
x = IntVar()
y = IntVar()

x.set(10)
y.set(10)

button = Button(window, text='Button', command=lambda: y.set(5))


def loop_this():

    if (x.get() == 10) and (y.get() != 5):
        button.place(x=0, y=0)

    if y.get() == 5:
        button.destroy()

    window.after(1000, loop_this)


loop_this()

window.mainloop()

In general, it's good to use Tkinter variables (IntVar, StringVar, BoolVar) when working with Tkinter. To replicate a scenario where y = 5, I made it be equal to 5 when the button is pressed, but it can be changed elsewhere in the code and it will work in the same way. The main thing is to put the thing into a function, attach it to the main window and run it in a loop. To do that we use .after(time_in_miliseconds_between_loops, function_to_loop_without_brackets)

and call the function before window.mainloop(). Hopefully this answers your question.

  • Related