Python Tkinter登录界面运行触发Entry对象KeyError报错求助
Tkinter登录界面KeyError问题排查
问题表现
运行基于Python Tkinter编写的登录界面时,点击登录按钮触发回调逻辑就抛出KeyError: <tkinter.Entry object .!entry>错误,调试近一小时未解决。
原始完整代码
from tkinter import * from tkinter import messagebox w=Tk() w.geometry('350x500') w.title('Sunset Panel') w.resizable(0,0) # 绘制渐变背景 j=0 r=10 for i in range(100): c=str(222222+r) Frame(w,width=10,height=500,bg="#"+c).place(x=j,y=0) j=j+10 r=r+1 Frame(w,width=250,height=400,bg='white').place(x=50,y=50) l1=Label(w,text='Username',bg='white') l=('Consolas',13) l1.config(font=l) l1.place(x=80,y=200) # 用户名输入框 e1=Entry(w,width=20,border=0) l=('Consolas',13) e1.config(font=l) e1.place(x=80,y=230) # 密码输入框 e2=Entry(w,width=20,border=0,show='*') e2.config(font=l) e2.place(x=80,y=310) l2=Label(w,text='Password',bg='white') l=('Consolas',13) l2.config(font=l) l2.place(x=80,y=280) # 输入框下划线 Frame(w,width=180,height=2,bg='#141414').place(x=80,y=332) Frame(w,width=180,height=2,bg='#141414').place(x=80,y=252) from PIL import ImageTk,Image imagea=Image.open("log.png") imageb= ImageTk.PhotoImage(imagea) label1 = Label(image=imageb, border=0, justify=CENTER) label1.place(x=115, y=50) # 登录按钮回调逻辑 def cmd(): db = open("Data.txt", "r") Username = e1 Password = e2 if Username == e1: d = [] f = [] for i in db: a,b = i.split(", ") b = b.strip() d.append(a) f.append(b) data = dict(zip(d, f)) if e1.get() == data[Username] and e2.get() == data[Password]: messagebox.showinfo("Login success", "Welcome") q=Tk() q.mainloop() else: messagebox.showwarning("Login failed dumb ass","Try again goofy") # 带悬停效果的按钮封装 def bttn(x,y,text,ecolor,lcolor): def on_entera(e): myButton1['background'] = ecolor myButton1['foreground']= lcolor def on_leavea(e): myButton1['background'] = lcolor myButton1['foreground']= ecolor myButton1 = Button(w,text=text, width=20, height=2, fg=ecolor, border=0, bg=lcolor, activeforeground=lcolor, activebackground=ecolor, command=cmd) myButton1.bind("<Enter>", on_entera) myButton1.bind("<Leave>", on_leavea) myButton1.place(x=x,y=y) bttn(100,375,'L O G I N','white','#994422') w.mainloop()
完整报错信息
Exception in Tkinter callback Traceback (most recent call last): File "C:\Users\ezneu\anaconda3\lib\tkinter\__init__.py", line 1892, in __call__ return self.func(*args) File "C:\Users\ezneu\OneDrive\Desktop\login\login.py", line 80, in cmd if e1.get() == data[Username] and e2.get() == data[Password]: KeyError: <tkinter.Entry object .!entry>
错误根因
报错核心是变量赋值和字典查询逻辑完全错误:
Username = e1、Password = e2两行把输入框组件对象赋值给了变量,而非用户在输入框填写的文本内容。Tkinter的Entry组件必须调用.get()方法才能拿到用户输入的字符串。- 后续
data[Username]相当于拿Entry组件对象当键查询存储账号密码的字典,但字典的键是从Data.txt读取的用户名字符串,不存在Entry对象对应的键,直接触发KeyError。 - 存在无效逻辑:
if Username == e1是恒成立判断(刚把e1赋值给Username),完全无作用;账号校验逻辑写反,data字典结构是{用户名: 密码},不存在data[用户名]=用户名、data[密码]=密码的对应关系。
修复方案
直接替换原有cmd()函数为以下修正版本即可:
def cmd(): # 获取输入框实际文本内容,自动去除首尾空格 input_user = e1.get().strip() input_pwd = e2.get().strip() # 空值校验 if not input_user or not input_pwd: messagebox.showwarning("输入错误", "用户名和密码不能为空") return # 读取账号文件,指定utf-8编码避免中文乱码 user_data = {} with open("Data.txt", "r", encoding="utf-8") as db: for line in db: line = line.strip() if not line: # 跳过文件空行 continue saved_user, saved_pwd = line.split(", ") user_data[saved_user] = saved_pwd.strip() # 校验账号密码:先判断用户名存在,再比对密码 if input_user in user_data and user_data[input_user] == input_pwd: messagebox.showinfo("登录成功", "欢迎使用") # 多窗口建议用Toplevel而非新建Tk实例,避免多事件循环冲突 q = Toplevel(w) q.geometry("300x200") q.mainloop() else: messagebox.showwarning("登录失败", "用户名或密码错误,请重试")
额外优化提示
- 确保
Data.txt和脚本在同一目录下,且每行格式严格为用户名, 密码(逗号后有空格,和split参数一致),否则会触发分割报错。 - Tkinter程序不建议创建多个
Tk()根实例,多窗口场景优先用Toplevel()组件,避免多事件循环导致程序异常。 - 文件操作优先用
with open()语法,会自动关闭文件,避免资源泄漏。
内容的提问来源于stack exchange,提问作者Ezneusch
相关产品推荐
相关产品推荐

