Tkinter PIN面板无论输入对错均提示‘Wrong PIN’问题排查
PIN校验GUI始终返回"Wrong PIN"的问题修复
问题根源
你的代码核心错误在于校验函数没有正确获取输入框的内容:
- 你定义了
number1_var = StringVar(),但从未将它与entry_PIN输入框绑定,所以number1_var.get()永远是空字符串,自然无法匹配预设的PIN码'1234'。 - 每次校验时都会新建一个Label,多次点击后会出现多个提示标签重叠的问题。
修复后的代码
from tkinter import * root = Tk() root.geometry('800x300') root.title('Check PIN') def button_add(number): number1 = entry_PIN.get() entry_PIN.delete(0, END) entry_PIN.insert(0, number1 + str(number)) pin = '1234' # 提前创建结果标签,避免重复创建 result_label = Label(root, text='') result_label.grid(row=6, column=1) def check_PIN(): # 直接从输入框获取内容 input_pin = entry_PIN.get() if input_pin == pin: result_label.config(text='Correct PIN!') else: result_label.config(text='Wrong PIN!') label_pin = Label(root, text='PIN:') label_pin.grid(row=0, column=0, padx=10, pady=10, sticky='e') entry_PIN = Entry(root) entry_PIN.grid(row=0, column=1, padx=10, pady=10) # 数字按钮部分 button1 = Button(root, text='1', width=7, command=lambda: button_add(1)) button2 = Button(root, text='2', width=7, command=lambda: button_add(2)) button3 = Button(root, text='3', width=7, command=lambda: button_add(3)) button4 = Button(root, text='4', width=7, command=lambda: button_add(4)) button5 = Button(root, text='5', width=7, command=lambda: button_add(5)) button6 = Button(root, text='6', width=7, command=lambda: button_add(6)) button7 = Button(root, text='7', width=7, command=lambda: button_add(7)) button8 = Button(root, text='8', width=7, command=lambda: button_add(8)) button9 = Button(root, text='9', width=7, command=lambda: button_add(9)) button1.grid(row=1, column=1, padx=10, pady=10) button2.grid(row=1, column=2, padx=10, pady=10) button3.grid(row=1, column=3, padx=10, pady=10) button4.grid(row=2, column=1, padx=10, pady=10) button5.grid(row=2, column=2, padx=10, pady=10) button6.grid(row=2, column=3, padx=10, pady=10) button7.grid(row=3, column=1, padx=10, pady=10) button8.grid(row=3, column=2, padx=10, pady=10) button9.grid(row=3, column=3, padx=10, pady=10) button_check = Button(root, text='Check PIN!', command=check_PIN) button_check.grid(row=5, column=1) root.mainloop()
关键修改点
- 移除了未使用的
number1_var变量,直接通过entry_PIN.get()获取输入框的内容 - 提前创建一个结果标签
result_label,校验时仅更新标签的文本内容,避免重复创建控件 - 简化了
check_PIN的调用方式,不需要使用lambda(直接传函数名即可)
内容的提问来源于stack exchange,提问作者Zelimir_Horvat_CRO
相关产品推荐
相关产品推荐

