Skip to main content
 首页 » 编程设计

python之Kivy/Python 中 super 的属性错误

2024年12月31日10txw1958

这是我在 .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 稍后将成为一个变量),但也许有更好的方法来做到这一点。

请您参考如下方法:

问题 - 属性错误

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

根本原因

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

解决方案

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

    kv 文件中的
  1. id 不是字符串。因此,从 id 中删除双引号。
  2. 将 self.ids.anchmath.ids.grdmath.ids.score.text 替换为 self.ids.score.text。

Kv language » Referencing Widgets

Warning

When assigning a value to id, remember that the value isn’t a string. There are no quotes: good -> id: value, bad -> id: 'value'

Kv language » self.ids

When your kv file is parsed, kivy collects all the widgets tagged with id’s and places them in this self.ids dictionary type property. That means you can also iterate over these widgets and access them dictionary style:

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 

输出