'Why won't it delete the previous labels after having added more labels?

I have recently been playing with tkinter (specifically buttons and labels) and so far I have created some simple code which displays a label, then using a button the label is removed, and through another button the label is brought back.

However, if I display two labels, only the most recent label can be removed, and I cannot find a way to remove the previous label. Here is the code so you can try it and look at the problem yourself:

import tkinter as tk

top = tk.Tk()

def on_click():
    global label
    label.after(10, label.destroy())

def restore():
    global label
    label = tk.Label (top, text = "INCOMING")
    label.pack(pady = 20)

tk.Button(top, text = "Delete?", command=on_click).pack()
tk.Button(top, text = "Restore?", command=restore).pack()

label = tk.Label(top, text = "TACTICAL NUKE")
label.pack(pady = 20)

top.mainloop()

How can I solve this?



Solution 1:[1]

The variable label is overwritten with a reference to the last label that is inserted. Therefore, you lose the references to the previous labels. You need to keep them somewhere in your program.

A good way to keep multiple related values in Python is to use a list. (Read about lists here.)

In this case you can use a list to implement a data structure called "stack", where you add values to the end (by using the append method of the list) and remove them from the end (by using the pop method).

The simplest possible change to make this work would be to replace the global variable label by a global variable labels which is a list that contains references to labels.

import tkinter as tk

top = tk.Tk()

def on_click():
    label = labels.pop()
    label.after(10, label.destroy())

def restore():
    label = tk.Label (top, text = "INCOMING")
    label.pack(pady = 20)
    labels.append(label)

tk.Button(top, text = "Delete?", command=on_click).pack()
tk.Button(top, text = "Restore?", command=restore).pack()

label = tk.Label(top, text = "TACTICAL NUKE")
label.pack(pady = 20)
labels = [label]

top.mainloop()

Now you need to consider what should happen after the original label has been removed.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1