在设定时间后删除标签 TkInter

Making a label remove after a set time TkInter

我的代码当前检查输入我的用户的用户名和密码,然后returns到带有相应文本的标签。

如下图:

from tkinter import *

def Login():
    global AnameEL
    global ApwordEL # More globals :D
    global ArootA
    global f1
    global f2

    ArootA = Tk() # This now makes a new window.
    ArootA.geometry('1280x720')
    ArootA.title('Admin login') # This makes the window title 'login'

    f1 = Frame(width=200, height=200, background="#D3D3D3")
    f2 = Frame(ArootA, width=400, height=200)

    f1.pack(fill="both", expand=True, padx=0, pady=0)
    f2.place(in_=f1, anchor="c", relx=.5, rely=.5)

    AnameL = Label(f2, text='Username: ') # More labels
    ApwordL = Label(f2, text='Password: ') # ^
    AnameL.grid(row=1, sticky=W)
    ApwordL.grid(row=2, sticky=W)

    AnameEL = Entry(f2) # The entry input
    ApwordEL = Entry(f2, show='*')
    AnameEL.grid(row=1, column=1)
    ApwordEL.grid(row=2, column=1)

    AloginB = Button(f2, text='Login', command=CheckLogin) # This makes the login button, which will go to the CheckLogin def.
    AloginB.grid(columnspan=2, sticky=W)

    ArootA.mainloop()

def CheckLogin():
    checkP = Label(f2, text='')
    checkP.grid(row=3, column=1)
    if AnameEL.get() == "test" and ApwordEL.get() == "123": # Checks to see if you entered the correct data.
        checkP.config(text='sucess')

    else:
        checkP.config(text='fail')

Login()

我想添加另一个功能,其中 2 秒后新代码行 运行 取决于登录 failed/success。

例如,当用户输入错误的登录名时,我希望文本 "fail" 在 2 秒后消失,如果用户输入正确的密码,我希望新功能是 运行 "success" 显示 2 秒后。

所以我尝试了这个: (还在我的代码顶部导入时间)

if AnameEL.get() == "test" and ApwordEL.get() == "123": # Checks to see if you entered the correct data.
    checkP.config(text='sucess')
    time.sleep(2)
    nextpage()
else:
    checkP.config(text='fail')
    time.sleep(2)
    checkP.config(text='')

def nextpage():
    f1.destroy()

然而,这并不成功。按下登录按钮后,它等待 2 秒,然后 运行 nextpage() 而不是显示 "success" 2 秒,然后 运行 nextpage() 并且对于不正确的登录,它直接进入 checkP.config(text='') 按下按钮 2 秒后。

我该如何解决这个问题?

感谢所有帮助, 谢谢

使用 time.sleep() 之前需要更新 root。此外,由于您正在处理 GUI,因此您应该更喜欢使用计时器而不是暂停执行。在这种情况下,Tkinter 自己的 after() 函数应该优于 time.sleep(),因为它只是将事件放在事件队列中而不是暂停执行。

after(delay_ms, callback=None, *args)

Registers an alarm callback that is called after a given time.

因此,根据您的示例:

if AnameEL.get() == "test" and ApwordEL.get() == "123":
    checkP.config(text='sucess')
    ArootA.update()
    time.sleep(2)
    nextpage()
else:
    checkP.config(text='fail')
    ArootA.update()
    time.sleep(2)
    nextpage()

after():

if AnameEL.get() == "test" and ApwordEL.get() == "123":
    checkP.config(text='sucess')
    ArootA.after(2000, nextpage)
else:
    checkP.config(text='fail')
    ArootA.after(2000, lambda : checkP.config(text=''))

您可能还想看看更新标签值的替代方法,以避免在主循环中时必须更新根目录(例如 Making python/tkinter label widget update?)。