Home > Enterprise >  Why destroy() doesn't work after 'label_x' is modified?
Why destroy() doesn't work after 'label_x' is modified?

Time:03-05

If I click on button 'xxx' after starting this little program, it destroys all widgets of the window except button 'greet me'... as it should... But if I write something into the yellow the entry field then click on 'greet me' and after that on 'xxx'... then for some reason the modified 'label_x' will not be deleted anymore... Also if I write multiple times some names in the entry box then click 'greet me' it is only writing on the previous label insted of destroying/deleting it first. Why is that and how could it be solved?

from tkinter import *
root = Tk()

# Creating an entry box
entry_box = Entry(root, width=10, relief="solid", bg="yellow" )
entry_box.grid(column=0, row=0)
entry_box.insert(3, "type name")

# Creating label widgets
label_x = Label(root, text="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
label_x.grid(column=0, row=2)
label_minus = Label(root, text="------------------------------")
label_minus.grid(column=0, row=3)

def greeter():
    label_x = Label(root, text="Welcome "   entry_box.get())
    label_x.grid(column=0, row=2)

# Creating greeter button
myButton = Button(root, text="greet me", command = lambda: [label_x.destroy(), greeter()])
myButton.grid(column=0, row=1)

x = Button(root, text="xxx", command = lambda: [label_x.destroy(), entry_box.destroy(), label_minus.destroy()])
x.grid(column=0, row=4)

root.mainloop()

CodePudding user response:

You're creating a new instance of label_x every time you're calling the greeter() function. A label_x which is different from the global label_x variable.

A quick fix is to declare label_x as a global variable inside the greeter() function. Like this:

def greeter():
    global label_x
    label_x = Label(root, text="Welcome "   entry_box.get())
    label_x.grid(column=0, row=2)

It might not be the best solution but it should work.

  • Related