Tkinter登录系统报错:'object has no attribute get' 求助
解决Tkinter登录系统中'object has no attribute get'的错误
错误根源
你遇到的'object has no attribute get'错误,核心原因是创建用户名/密码输入框时,错误地将Entry()和place()链式调用的结果赋值给了类属性:
self.UserName=Entry(...).place(...)
place()方法的返回值是None,而非Entry对象,所以self.UserName实际是None,自然没有get()方法。
此外代码还有两处小问题:
- 登录验证的最后一个条件应该用
and(需用户名和密码同时正确),而非or - 欢迎提示框需要调用
messagebox.showinfo(),而非直接调用messagebox()
修正方案
将输入框的对象创建和布局操作分开执行:先实例化Entry对象并赋值给类属性,再单独调用place()完成布局。同时修正验证逻辑和消息框调用。
修正后的完整代码
from tkinter import * from PIL import ImageTk from tkinter import messagebox class Login(): def __init__(self, root): self.root = root self.root.title("Login system") self.root.geometry("1920x1080") # 背景图片 self.bg=ImageTk.PhotoImage(file="Image/1.jpg") self.bg_image=Label(self.root, image=self.bg).place(x=0, y=0, relwidth=1, relheight=1) # 登录框架 FrameLogin = Frame(self.root, bg="White") FrameLogin.place(x=390, y=150, width=500, height=488) # 登录标题 title=Label(FrameLogin, text="Login Here", font=("Impact", 35, "bold"), fg="#850101", bg="white").place(x=130, y=30) # 用户名输入框:先创建对象,再布局 UserUserName=Label(FrameLogin, text="Username", font=("Impact", 15), fg="black", bg="white").place(x=70, y=160) self.UserName=Entry(FrameLogin, font=("Goudy old style", 15), fg="grey", bg="white") self.UserName.place(x=70, y=190, width=320, height=35) # 密码输入框:先创建对象,再布局(增加show="*"隐藏输入内容) UserPassword=Label(FrameLogin, text="Password", font=("Impact", 15,), fg="black", bg="white").place(x=70, y=230) self.Password=Entry(FrameLogin, font=("Goudy old style", 15), fg="grey", bg="white", show="*") self.Password.place(x=70, y=260, width=320, height=35) # 忘记密码按钮 ForgetButton = Button(FrameLogin, text="Forget Password", bd=0, font=("Goudy old style", 10), fg="blue", bg="white").place(x=70, y=310) # 登录按钮 LoginButton = Button(FrameLogin, command=self.checker, cursor="hand2", text="Login", bd=0, font=("Impact", 20), fg="white", bg="#850101").place(x=120, y=350, width=230, height= 37) def checker(self): username = self.UserName.get() password = self.Password.get() if username == "" or password == "": messagebox.showerror("Error", "Input required", parent=self.root) elif username != "Abemelek" or password != "1234": messagebox.showerror("Error", "Username or password incorrect", parent=self.root) elif username == "Abemelek" and password == "1234": messagebox.showinfo("Welcome", f"Welcome {username}") root = Tk() obj = Login(root) root.mainloop()
额外优化:给密码输入框添加show="*"属性,输入时自动隐藏密码,提升登录安全性。
内容的提问来源于stack exchange,提问作者Abemelek Ermias
相关产品推荐
相关产品推荐

