简体   繁体   English

从Tkinter窗口清除所有标签

[英]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. 因此,我是tkinter的新手,但是我有想要的工作,直到某个时候。 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: 这就是我的意思:

在此处输入图片说明

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. 我尝试了通常的info.destoy()info.forget() ,但是它们仅适用于该函数中使用的最后一个标签。 Should I have grouped all labels or something? 我应该将所有标签分组吗?

As PM 2Ring suggested it is usually useful to append labels to a list for future ref: 正如PM 2Ring建议的那样,将标签附加到列表中以供将来参考通常是有用的:

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: 如果您不想要列表,并且确定要清除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. 如果要保留地图标签,则必须按照我的说明制作自己的列表,而无需在其中添加info

I would recommend using: 我建议使用:

info.pack_forget()

For each pack you created you must do it in the format: 对于您创建的每个包,您都必须采用以下格式:

packname.pack_forget()

Which if you have a lot of packs is impractical, but otherwise it works very well. 如果您有很多包装,那是不切实际的,但否则效果很好。

This also makes it very easy to selectively remove some labels and leave others as it will not purge all packs that you placed. 这也使得很容易有选择地移除一些标签并留下其他标签,因为这不会清除您放置的所有包装。

Just use: 只需使用:

root.children.clear

After clearing screen just input map and functions again... 清除屏幕后,只需输入地图并再次运行...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM