首页 > 解决方案 > 在屏幕上放置一个 tkinter 标签几秒钟然后销毁它

问题描述

因此,当您运行 tkinter 标签(和整个窗口)下方的代码时,几秒钟内根本没有出现,然后窗口显示时没有标签。我想显示标签几秒钟,然后让它在几秒钟后消失。

from tkinter import *
import time

root = Tk()

busted_display = Label(root, text="My Label Widget", 
    font=("arial", "15"))
busted_display.place(x=0, y=0)
print("it ran")
time.sleep(3)
print("and then this ran")
busted_display.destroy()

root.mainloop()

标签: python-3.xtkinter

解决方案


You can't use time.sleep in an event driven program like a GUI. In tkinter, the answer to timed operations is the after() method, which runs the code you give it after a certain amount of milliseconds.

from tkinter import *

root = Tk()

busted_display = Label(root, text="My Label Widget", font=("arial", "15"))
busted_display.place(x=0, y=0)
root.after(2000, busted_display.destroy)

root.mainloop()

推荐阅读