如何避免AttributeError:“\tkinter.tkapp”对象没有属性“PassCheck”

2024-06-13 05:30:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经阅读了之前关于这个错误的文章,但是我不能确定我做错了什么。请有人帮助我理解我做错了什么,谢谢。

   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()

Tags: textselfconfiglendefbuttonpasswordlabel
1条回答
网友
1楼 · 发布于 2024-06-13 05:30:11

是什么引发了这个错误?

您将收到以下错误消息:

AttributeError: '_tkinter.tkapp' object has no attribute 'PassCheck'

因为当初始化Passwordchecker()的实例时,它会偶然发现__init__()mainloop()方法,该方法不允许程序识别属于该实例的任何其他方法。根据经验,永远不要在__init__()内部运行mainloop()。这完全修复了上面的错误消息。但是,我们还有其他事情要解决,为此,让我们重新设计您的计划:

设计

最好使用在__init__()内部调用的其他方法来绘制图形用户界面。我们称之为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()

演示

下面是运行程序的屏幕截图:

enter image description here

相关问题 更多 >