我已经阅读过有关此错误的先前帖子,但无法确定我在做什么错。请有人可以帮助我了解我在做什么错,谢谢。
from tkinter import *
class Passwordchecker():
def __init__(self):
self= Tk()
self.geometry("200x200")
self.title("Password checker")
self.entry=Entry(self)
self.entry.pack()
self.button=Button(self,text="Enter",command= lambda: self.PassCheck(self.entry,self.label))
self.button.pack()
self.label=Label(self,text="Please a password")
self.label.pack()
self.mainloop()
def PassCheck(self1,self2):
password = self1.get()
if len(password)>=9 and len(password)<=12:
self2.config(text="Password is correct")
else:
self2.config(text="Password is incorrect")
run = Passwordchecker()
Run Code Online (Sandbox Code Playgroud)
您收到此错误消息:
AttributeError: '_tkinter.tkapp' object has no attribute 'PassCheck'
Run Code Online (Sandbox Code Playgroud)
因为当初始化 的实例时Passwordchecker(),它会偶然发现mainloop()您的方法__init__(),这不会让您的程序识别属于该实例的任何其他方法。根据经验,永远不要跑mainloop()进去__init__()。这完全修复了您上面收到的错误消息。但是,我们还有其他问题需要解决,为此,让我们重新设计您的程序:
最好采用在内部调用的其他方法__init__()来绘制 GUI。我们就这样称呼它吧initialize_user_interface()。
当涉及到 时PassCheck(),您需要首先将对象本身传递给此方法。这意味着传递给此方法的第一个参数是self。事实上,这是我们需要的唯一参数,PassCheck(self)因为您可以从此方法访问您无用地传递给它的剩余参数。
这是您需要的完整程序:
import tkinter as tk
class Passwordchecker(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.parent = parent
self.initialize_user_interface()
def initialize_user_interface(self):
self.parent.geometry("200x200")
self.parent.title("Password checker")
self.entry=tk.Entry(self.parent)
self.entry.pack()
self.button=tk.Button(self.parent,text="Enter", command=self.PassCheck)
self.button.pack()
self.label=tk.Label(self.parent,text="Please a password")
self.label.pack()
def PassCheck(self):
password = self.entry.get()
if len(password)>=9 and len(password)<=12:
self.label.config(text="Password is correct")
else:
self.label.config(text="Password is incorrect")
if __name__ == '__main__':
root = tk.Tk()
run = Passwordchecker(root)
root.mainloop()
Run Code Online (Sandbox Code Playgroud)
下面是程序运行的截图: