W.Hunt W.Hunt - 1 month ago 11
Python Question

Clearing all Labels from a tkinter window

So I'm new to tkinter, but I've got what I want working, up to a certain point.
I'm not sure I've set it up correctly, but I've got a world map with buttons on the right, and an events log on the left, which fills up with labels as stuff happens.
Issue is that after a little while, the whole log fills up.
What is the best way to delete all the labels, or maybe delete the oldest (top) label each time?
Here's what I mean:

enter image description here

Defined here:

root=Tk()
Map=PhotoImage(file="C:/Users/Willam/Desktop/CWProgram/map2.gif")
background=Label(root,image=Map).place(x=100,y=0,relwidth=1,relheight=1)
Title=Label(root,text=' LOG').pack(anchor=NW)


And I create my labels like this:

info=Label(root,text='Select a sector to move units from',wraplength=170)
info.pack(anchor=NW)


I tried the usual
info.destoy()
and
info.forget()
, but these only work on the last label used in that function.
Should I have grouped all labels or something?

Answer

As PM 2Ring suggested it is usually useful to append labels to a list for future ref:

tmp = Label(...)
labels.append(tmp)

then just:

foreach label in labels: label.destroy()

If you do not want a list, and you're sure you want to clear everything in root:

foreach label in root.children.values(): label.destroy()

The children dict always holds the objects contained within. If you want to keep the map label, you will have to make your own list as I showed, without appending info into it.

Comments