使用 tkinter 在 python GUI 中循环(几次尝试后阻止密码)

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

希望您度过愉快的一天。 我创建了一个输入密码界面。输入正确的密码后,它应该显示在标签中授予的访问权限,这与我的代码配合良好。但是,如果密码不正确,我只想尝试 3 次。如果您第一次和第二次输入错误的密码,则应显示“密码错误”。经过最后的尝试后,它应该显示“帐户被阻止”。问题是当涉及到错误的密码和第一次尝试时,它直接显示“帐户被阻止” 这是我到目前为止所得到的,

from tkinter import *
root = Tk()
root.geometry("300x300")

# Creating Button Command
def password():
    correct_password = "123"
    enter_the_password = pass_entry.get()
    number_of_try=0
    number_of_max_try=3
    max_try=""

    while enter_the_password!=correct_password and max_try!="reached":
        if number_of_try<number_of_max_try:
            enter_the_password
            number_of_try=number_of_try+1
            if enter_the_password!=correct_password:
                response= "Incorrect Password"
        else:
            max_try="reached"

    if max_try=="reached":
        response= "Too many attempts. Account blocked"
    else:
        response= "Access Granted"
    
    pass_label.config(text=response)
    pass_entry.delete(0, END)
    
# Creating widget 
pass_entry=Entry(root, width=30)
pass_entry.pack(pady=5)
done_button= Button(root, text="Press", command=password).pack(pady=10)

pass_label= Label(root, width=30)
pass_label.pack(pady=10)

root.mainloop()

   
python python-3.x tkinter while-loop
1个回答
1
投票

您的

while
循环会立即重新进入,而不会让用户输入另一个密码。事实上,您不需要该循环,因为
root.mainloop()
已经提供了它。

相反,您应该删除

while
循环,并在函数外部初始化变量
password
。每次按下
done_button
时,功能
password
应仅检查密码一次。

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