如何在绑定到按钮的函数中设置尝试计数器?
How to set up an attempts counter in a function bound to a button?
我一直在尝试设置登录屏幕,并且在过去 2 天里一直卡在这个特定问题上。为了清晰和易于使用,我想定义一个函数来跟踪错误的用户名密码组合的尝试次数,并将该函数绑定到回车按钮。我尝试了 while 循环以及基本的 if x = x AND attempt < y: 样式,但都没有用。在搜索了一个类似的问题后,我找到了一个建议使用 for 循环的答案,这似乎在视觉上和实践上都更有意义。当我输入错误的通行证组合并按回车键时,我会立即收到访问被拒绝的消息,而不是左侧的尝试。我怀疑循环在没有按下回车按钮的情况下重复自己并一次完成尝试。
def checkname():
attempt = 4
for attempt in range(attempt,0,-1):
usern = entry_name.get()
passw = entry_pass.get()
if (usern, passw) in names:
message.configure(text = "Access Granted!")
else:
message.configure(text = "{0} attempts left".format(attempt) )
else:
message.configure(text="Access Denied!")
我考虑过在函数外部创建一个全局变量并确保它跟踪尝试,但它似乎给出了未绑定的局部变量错误。任何帮助将不胜感激。
不需要循环,因为 tkinter GUI 已经有一个循环 运行 (mainloop
)。只需在函数中增加一个全局变量,并在数字太大时停止:
...
login_button = tk.Button(..., command=do_login)
...
attempts = 0
def do_login():
global attempts
attempts = attempts + 1
if attempts > 4:
<code to handle too many attempts>
else
<code to handle an attempt>
当然,如果您使用的是 classes,请将 attempts
设为 class 的属性而不是全局变量。
我一直在尝试设置登录屏幕,并且在过去 2 天里一直卡在这个特定问题上。为了清晰和易于使用,我想定义一个函数来跟踪错误的用户名密码组合的尝试次数,并将该函数绑定到回车按钮。我尝试了 while 循环以及基本的 if x = x AND attempt < y: 样式,但都没有用。在搜索了一个类似的问题后,我找到了一个建议使用 for 循环的答案,这似乎在视觉上和实践上都更有意义。当我输入错误的通行证组合并按回车键时,我会立即收到访问被拒绝的消息,而不是左侧的尝试。我怀疑循环在没有按下回车按钮的情况下重复自己并一次完成尝试。
def checkname():
attempt = 4
for attempt in range(attempt,0,-1):
usern = entry_name.get()
passw = entry_pass.get()
if (usern, passw) in names:
message.configure(text = "Access Granted!")
else:
message.configure(text = "{0} attempts left".format(attempt) )
else:
message.configure(text="Access Denied!")
我考虑过在函数外部创建一个全局变量并确保它跟踪尝试,但它似乎给出了未绑定的局部变量错误。任何帮助将不胜感激。
不需要循环,因为 tkinter GUI 已经有一个循环 运行 (mainloop
)。只需在函数中增加一个全局变量,并在数字太大时停止:
...
login_button = tk.Button(..., command=do_login)
...
attempts = 0
def do_login():
global attempts
attempts = attempts + 1
if attempts > 4:
<code to handle too many attempts>
else
<code to handle an attempt>
当然,如果您使用的是 classes,请将 attempts
设为 class 的属性而不是全局变量。