如何解决登录系统的代码中的Tkinter错误:AttributeError:'str'对象没有属性'tk'
我是Python的新手,我正在尝试使用Tkinter设计一个简单的登录系统作为第一个小项目。这是我写的(我知道网格结构仍然很糟糕,但是我需要一些实践):
from tkinter import *
from tkinter.ttk import *
from tkinter import ttk
import tkinter as tk
from PIL import ImageTk,Image
class Login_system():
user = "user"
passw = "pw"
def __init__(self,root):
self.root = root
self.root.title("Login System Prova")
self.entry = tk.Entry(root)
self.root.geometry("500x400+400+400")
stvar = tk.StringVar()
stvar.set("one")
self.option = tk.OptionMenu(root,stvar,"one","two","three")
frame = Frame(self.root)
frame.grid(row = 0,column = 0,sticky = N)
self.option = tk.OptionMenu(frame,"three")
self.option.grid(row = 0,column = 1,sticky = NW)
Label(frame,text = "Your Username").grid(row=1,column=0,sticky=NW,pady = 2)
self.username = Entry()
self.username.grid(row = 1,column=1,pady=2)
Label(frame,text = "Your Password").grid(row=3,pady=2)
self.password = Entry(show = "*")
self.password.grid(row = 2,pady=2)
ttk.Button(frame,text = "Login",command = self.login_user).grid(row = 6,pady=2)
Checkbutton1 = Checkbutton(frame,text = "Keep me on-line").grid(row = 7,sticky = W,columnspan= 1)
def login_user(self):
if self.username.get() == self.user and self.password.get() == self.passw:
root.destroy()
#newroot = Tk()
#application = ...(newroot)
#newroot.mainloop()
else:
self.message = Label("Wrong Username or Password")
self.message.grid(row = 6,column = 2)
if __name__ == "__main__":
root = tk.Tk()
Login_system = Login_system(root)
root.mainloop()
如果我输入正确的初始化用户名和密码,该窗口将按预期消失,但是如果我输入了错误的用户名和密码,而收到消息“错误的用户名或密码”,则会出现此错误:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\admin\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py",line 1883,in __call__
return self.func(*args)
File "C:\Users\admin\Desktop\Python\GUI APP\login_system_new.py",line 75,in login_user
self.message = Label("Wrong Username or Password")
File "C:\Users\admin\AppData\Local\Programs\Python\Python38-32\lib\tkinter\ttk.py",line 759,in __init__
Widget.__init__(self,master,"ttk::label",kw)
File "C:\Users\admin\AppData\Local\Programs\Python\Python38-32\lib\tkinter\ttk.py",line 557,in __init__
tkinter.Widget.__init__(self,widgetname,kw=kw)
File "C:\Users\admin\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py",line 2561,in __init__
BaseWidget._setup(self,cnf)
File "C:\Users\admin\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py",line 2530,in _setup
self.tk = master.tk
AttributeError: 'str' object has no attribute 'tk'
有人建议我该怎么避免吗?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。