在设定的时间TkInter之后删除标签

问题描述 投票:0回答:1

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

如下所示:

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秒后运行新的代码行,具体取决于登录失败/成功。

例如,当用户输入错误的登录时,我希望文本“失败”在2秒后消失,如果用户输入正确的密码,我希望在显示“成功”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()而不是显示“成功”2秒然后运行nextpage(),并且对于不正确的登录,它会在按下按钮2秒后直接进入checkP.config(text='')

我该如何解决这个问题?

感谢所有帮助。

python python-3.x time tkinter python-3.5
1个回答
1
投票

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

之后(delay_ms,callback = None,* args)

注册在给定时间后调用的警报回调。

所以,根据你的例子:

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?)时更新root。

© www.soinside.com 2019 - 2024. All rights reserved.