如何避免 AttributeError: '_tkinter.tkapp' 对象没有属性 'PassCheck'

问题描述 投票:0回答:1

我已阅读之前有关此错误的帖子,但无法确定我做错了什么。请有人帮助我理解我做错了什么?

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()
python tkinter
1个回答
5
投票

什么触发了错误?

您收到此错误消息:

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

因为当初始化

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

演示

这是运行程序的截图:

© www.soinside.com 2019 - 2024. All rights reserved.