Python Tkinter密码修改程序校验始终返回false问题排查
问题根因
密码校验始终返回false的核心bug是新密码长度判断的变量名写错了:
你写的长度校验逻辑是len(s) >= 8,但check_password函数内从未定义过变量s,如果你在全局作用域定义过s(比如是空字符串、其他长度不足8位的内容),这个判断永远不成立,会直接走校验失败分支输出false,哪怕输入的新密码完全符合规则,也到不了后面的两次密码一致性校验逻辑。
另外你在函数内用global声明tkinter控件的写法是多余的,只要控件定义在全局作用域,函数可以直接访问,这部分不影响功能但没有必要。
额外排查点:请确认存储正确旧密码的
oldpassword变量是字符串类型,和输入框获取到的字符串内容完全一致,不要出现一个存数字、一个是字符串的情况,否则旧密码校验永远不通过。
修复后代码
把原来的check_password函数替换成下面的版本即可,修复了变量名错误,同时简化了多层嵌套的判断逻辑,用提前返回的写法降低后续出bug的概率:
def check_password(): # 获取三个输入框的输入内容 oldpasswordcheck = oldpassword_entry.get() newpasswordcheck = newpassword_entry.get() newpasswordconfirmedcheck = newpasswordconfirmed_entry.get() # 逐层校验,不满足规则直接返回失败 # 1. 校验旧密码是否正确 if oldpasswordcheck != oldpassword: print("false") return # 2. 校验新密码复杂度:包含大写、小写、数字,长度不少于8位 has_upper = any(c.isupper() for c in newpasswordcheck) has_lower = any(c.islower() for c in newpasswordcheck) has_digit = any(c.isdigit() for c in newpasswordcheck) valid_len = len(newpasswordcheck) >= 8 if not (has_upper and has_lower and has_digit and valid_len): print("false") return # 3. 校验两次输入的新密码完全一致 if newpasswordcheck != newpasswordconfirmedcheck: print("false") return # 所有校验通过 print("true") showoldpasswordchange_label.configure(text=newpasswordconfirmedcheck) okaybutton_button = ttk.Button(root, text= "Okay", width= 20, command= check_password)
原有控件定义说明
你之前写的界面控件定义没有问题,只要这些控件是定义在函数外的全局作用域,修复后的函数就能正常访问:
showoldpassword_label = tk.Label(root, text = 'Current Password: ', font=('calibre',10, 'bold')) showoldpasswordchange_label = tk.Label(root, text = 'PasswordExample', font=('calibre',10, 'bold')) oldpassword_label = tk.Label(root, text = 'Old Password: ', font=('calibre',10, 'bold')) oldpassword_entry = tk.Entry(root, font=('calibre',10,'normal'), show = '*') newpassword_label = tk.Label(root, text = 'New Password: ', font=('calibre',10, 'bold')) newpassword_entry = tk.Entry(root, font=('calibre',10,'normal'), show = '*') newpasswordconfirmed_label = tk.Label(root, text = 'Confirm Password: ', font=('calibre',10, 'bold')) newpasswordconfirmed_entry = tk.Entry(root, font=('calibre',10,'normal'), show = '*')
程序运行界面参考

内容的提问来源于stack exchange,提问作者Theo Smith
相关产品推荐
相关产品推荐

