在 Tkinter 上显示标签一段固定的时间

问题描述

我正在使用 Tkinter 在 Python 2.7 中创建一个 GUI 应用程序.我有这段代码:

I'm creating a GUI application in Python 2.7 using Tkinter. I have this piece of code:

vis=Label(pur,text='Purchase Added successfully',font=(8))
vis.place(x=150,y=460)

我想知道是否有任何方法可以在有限的时间(约 3 秒)内显示已成功购买"标签,然后它会消失.这是因为我有兴趣在当前购买之后添加新的购买",并且不希望成功消息重叠.

I wanna know if there's any way to display the Label 'Purchase Added Successfully' for a limited amount of time(~3 seconds) and then it would disappear. This is because I'm interested in adding a new 'purchase' after the current one, and don't want the success messages to overlap.


解决方案

根据项目模式有很多种方法,都基于语法:

There are many ways depending on the project pattern, all based on the syntax :

vis=Label(pur,text='Purchase Added successfully',font=(8))
vis.place(x=150,y=460)
vis.after(3000, function_to_execute)

彻底毁灭

如果您不想怀疑标签是否已创建、隐藏或为空,并且主要避免可能的内存泄漏(感谢 Bryan Oakley 评论):

If you don't want to wonder whether the label is already created, hidden or empty, and mostly avoid possible memory leaks (thanks to Bryan Oakley comment):

vis.after(3000, lambda: vis.destroy() )

但是你需要为每次购买创建一个全新的Label.

But then you need to create a fresh new Label for every purchase.

捉迷藏

以下方法允许在不破坏标签的情况下禁用标签的显示.

The following method allows to disable the display of the Label without destroying it.

vis.after(3000, lambda: vis.place_forget() )
#vis.after(3000, lambda: vis.grid_forget() ) # if grid() was used
#vis.after(3000, lambda: vis.pack_forget() ) # if pack() was used

然后您可以使用 vis.place(x=150,y=460)

文本橡皮擦

另一种方式,可能不太有趣,除非您更喜欢在容器小部件中保留一个空标签:

Another way, maybe less interesting, unless you prefer keeping an empty Label in the container widget:

vis.after(3000, lambda: vis.config(text='') )

(请注意,您可以将文本替换为 vis.config(text='blabla') 以便下次购买)

(Note that you can replace the text with vis.config(text='blabla') for the next purchase)

相关文章