Tkinter按钮没有React,因为我预期与python睡眠

flseospp  于 2023-01-24  发布在  Python
关注(0)|答案(1)|浏览(85)

我试图使一个登录按钮的密码 Flink 红色,然后回到正常时,不正确的密码键入,但它是不工作的。

#   A program creates a window on your screen using Tkinter.
import tkinter as tk
import time 
def testmybutton():
    Correctpassword = "Pa$$w0rd"
    frame_auth.tkraise()
    password = ent_password.get()
    username = ent_username.get()
    if password == Correctpassword:
        lbl_new.config(text='Logged in')
    else:
        frame_login.tkraise()
        ent_password.config(bg="red")
        time.sleep(2)
        ent_password.config(bg='white')
# main window
root = tk.Tk()
root.wm_geometry("200x150")
root.title('Authorization')

frame_login = tk.Frame(root)
frame_login.grid(row=0, column=0, stick='NEWS')

lbl_username = tk.Label(frame_login, text='Username:', cursor="heart", bg='white', relief='flat')
lbl_username.pack()

ent_username = tk.Entry(frame_login, bd=5)
ent_username.pack(padx=40)

lbl_password = tk.Label(frame_login, text='password:', cursor="heart", bg='white', relief='flat')
lbl_password.pack()

ent_password = tk.Entry(frame_login, bd=5, show='+')
ent_password.pack(padx=40)

lbl_button = tk.Button(frame_login, text='LOG IN:', cursor="pirate", bg='white', relief='raised', command=testmybutton)
lbl_button.pack()

tk.Label(frame_login,text="Password:",font="Courier")

frame_auth = tk.Frame(root)
frame_auth.grid(row=0, column=0, stick='NEWS')

lbl_new = tk.Label(frame_auth, text='New Window:', cursor="heart", bg='white', relief='flat')
lbl_new.pack()

frame_login.tkraise()


root.mainloop()`

我试过创建第二个函数,并在测试我的按钮函数中调用它,但是也不起作用。

llmtgqce

llmtgqce1#

您应该避免在tkinter应用程序中的任何地方使用sleep,因为它会导致主UI线程/事件循环在睡眠时挂起。
相反,您应该使用内置的tkinter.after()方法,该方法允许您在给定的毫秒数之后调用函数

def testmybutton():
    Correctpassword = "Pa$$w0rd"
    frame_auth.tkraise()
    password = ent_password.get()
    username = ent_username.get()
    if password == Correctpassword:
        lbl_new.config(text='Logged in')
    else:
        frame_login.tkraise()
        ent_password.config(bg="red")
        # call this function anonymously after 2000mS (2 seconds)
        root.after(lambda: ent_password.config(bg='white'), 2000)

这里我使用root.after(),因为rootTk的示例

相关问题