【问题标题】:Python : AttributeErrorPython:属性错误
【发布时间】:2013-07-01 19:54:20
【问题描述】:

我得到一个似乎无法解决的 AttributeError。 我正在处理两个班级。

第一堂课是这样的。

class Partie:
    def __init__(self):
        # deleted lines
        self.interface = Interface(jeu=self)

    def evaluerProposition(self):
        # computations
        self.interface.afficherReponse()

介绍第二类(在单独的文件中)。

class Interface:
    def __init__(self, jeu):
        self.jeu = jeu
        self.root = tkinter.Tk()
        # stuff

    def onClick(self, event):
        # talk
        self.jeu.evaluerProposition()

    def afficherReponse(self):
        # stuff

我是从

开始的
partie = Partie()

我的小部件上的所有操作都可以正常工作,直到某些点击事件引起

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python33\lib\tkinter\__init__.py", line 1442, in __call__
    return self.func(*args)
  File "C:\Users\Canard\Documents\My Dropbox\Python\AtelierPython\Mastermind\classeInterface.py", line 197, in clic
    self.jeu.evaluerProposition()
  File "C:\Users\Canard\Documents\My Dropbox\Python\AtelierPython\Mastermind\classeJeu.py", line 55, in evaluerProposition
    self.interface.afficherReponse()
AttributeError: 'Partie' object has no attribute 'interface'

我输入了解释器

>>> dir(partie)

并得到一个长列表作为回报,属性中包含“接口”。

也输入了

>>> partie.interface
<classeInterface.Interface object at 0x02C39E50>

所以属性似乎存在。

按照以前的帖子中的建议,我检查了实例名称与模块名称不一致。 我很困惑。

【问题讨论】:

  • 我不确定,但我认为您在 Partie 的构造函数中传递 self 作为 Interface() 的参数这一事实并不健康......跨度>
  • @kren470 我不认为 Python 关心你定义类的顺序。
  • @2rs2ts 确实看起来不健康。我创建了第三个类Master,它有两个属性interfacepartie。然后我可以通过 self.partie.interface = self.interface self.interface.partie = self.partie 链接这两个对象
  • 你在哪里使用onClick方法?你能显示那个代码吗?我的猜测是,您正在执行类似Button(..., command=self.onClick()) 的操作(请注意函数名称后面的())。如果是,则需要删除()(例如:Button(..., command=self.onClick)。
  • 这段代码没有明显的错误。但是您应该发布函数interface.afficherResponse 的代码,因为这是导致错误的原因。

标签: python tkinter attributeerror


【解决方案1】:

很可能,在您没有向我们展示的某些代码中,您正在执行以下操作:

self.some_button = tkinter.Button(..., command=self.interface.onClick())

注意onClick() 上的尾随()。这将导致在创建按钮时调用onClick 方法,这可能是在您的构造函数完成构造Partie 类的实例之前。

【讨论】: