首页 > 解决方案 > Kivy/Python 中的 super 属性错误

问题描述

这是导致问题的 .py 端的代码摘录:

class ScreenMath(Screen):

    def __init__(self,**kwargs):
        super(ScreenMath,self).__init__(**kwargs)
        self.ids.anchmath.ids.grdmath.ids.score.text = str("Score:" + "3")

而 .kv 方面:

<ScreenMath>:
    AnchorLayout:
        id: "anchmath"
        ...    
        GridLayout:
            id: "grdmath"
            ...
            Button:
                id: "score"

当我运行代码时,发生 AttributeError :

    File "kivy\properties.pyx", line 841, in kivy.properties.ObservableDict.__getattr__
 AttributeError: 'super' object has no attribute '__getattr__'

如您所见,我想在屏幕启动时更改值的文本(3 稍后将成为变量),但也许有更好的方法来做到这一点。

标签: pythonkivysuperattributeerrorkivy-language

解决方案


问题 - AttributeError

    File "kivy\properties.pyx", line 841, in kivy.properties.ObservableDict.__getattr__
 AttributeError: 'super' object has no attribute '__getattr__'

根本原因

Kivy 无法找到该属性,因为id您的 kv 文件中的 s 被分配了字符串值。

解决方案

要解决此问题,需要进行以下更改。

  1. idkv 文件中的 s 不是字符串。因此,从id.
  2. 替换self.ids.anchmath.ids.grdmath.ids.score.textself.ids.score.text

Kv 语言 » 参考小部件

警告

为 id 赋值时,请记住该值不是字符串。没有引号:好 -> id: value, bad -> id: 'value'

Kv 语言 » self.ids

当你的 kv 文件被解析时,kivy 会收集所有带有 id 标记的小部件,并将它们放在这个 self.ids 字典类型属性中。这意味着您还可以遍历这些小部件并访问它们的字典样式:

for key, val in self.ids.items():
    print("key={0}, val={1}".format(key, val))

片段 - Python 代码

class ScreenMath(Screen):

    def __init__(self,**kwargs):
        super(ScreenMath,self).__init__(**kwargs)
        self.ids.score.text = str("Score:" + "3")

片段-kv 文件

<ScreenMath>:
    AnchorLayout:
        id: anchmath
        ...    
        GridLayout:
            id: grdmath
            ...
            Button:
                id: score

输出

图像01


推荐阅读