You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python Tkinter开发登录GUI时出现AttributeError问题求助

问题分析与解决

核心错误原因

  • Entry对象被覆盖为None:在login()函数中,你将Entry()创建与.pack()写在同一行(如username_login = Entry(...).pack())。.pack()方法返回None,导致原本应存储Entry对象的username_login、password_login变量最终变为None,调用.get()时自然抛出AttributeError。
  • textvariable绑定错误:Entry的textvariable参数需绑定你定义的StringVar对象,但你错误绑定了Label对象(且Label.pack()返回None,等同于绑定了None)。

其他代码问题

  • 变量名笔误:check_login()中打开文件时用了未定义的login_username_login,实际应使用获取到的用户名变量login_username。
  • 文件读取逻辑错误:file.readlines()返回的是列表,直接与字符串拼接比较逻辑错误,需读取内容后去除换行符再比较。
  • 窗口对象未定义:check_login()中使用的screen1未定义,应改为登录窗口top。

修正后的完整代码

登录窗口函数

def login():
    global username_login_entry, password_login_entry, top
    username_var = StringVar()
    password_var = StringVar()
    top = Toplevel()
    top.title("Login")
    top.geometry("500x300")
    top["bg"]="#DFA0F1"
    
    Label(top, text="Login:", bg="#F3EF9D").pack()
    
    # 分开创建组件与布局,避免返回值覆盖对象
    username_label = Label(top, text="Username", bg="#AAF7C7")
    username_label.pack()
    username_login_entry = Entry(top, textvariable=username_var)
    username_login_entry.pack()
    
    password_label = Label(top, text="Password", bg="#AAF7C7")
    password_label.pack()
    password_login_entry = Entry(top, textvariable=password_var, show="*")
    password_login_entry.pack()
    
    login_btn = Button(top, text="Login", height="1", width="10", bg="#AEF0F5", command=check_login)
    login_btn.pack()

登录校验函数

def check_login():
    login_username = username_login_entry.get().strip()
    login_password = password_login_entry.get().strip()
    
    try:
        with open(f"{login_username}.txt", "r") as file:
            stored_password = file.read().strip()
            if stored_password == login_password:
                Label(top, text="Login Success", fg="green", bg="#DFA0F1", font=("calibri", 11)).pack()
            else:
                Label(top, text="Username/Password incorrect", fg="red", bg="#DFA0F1").pack()
    except FileNotFoundError:
        Label(top, text="Username does not exist", fg="red", bg="#DFA0F1").pack()

内容的提问来源于stack exchange,提问作者thomas3451

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 06:40:23