【问题标题】:Attribute error with super in Kivy/PythonKivy/Python 中的 super 属性错误
【发布时间】:2018-08-25 13:35:52
【问题描述】:

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

【问题讨论】:

    标签: python kivy super attributeerror kivy-language


    【解决方案1】:

    问题 - AttributeError

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

    根本原因

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

    解决方案

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

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

    Kv language » Referencing Widgets

    警告

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

    Kv language » 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
    

    输出

    【讨论】:

    • __init__() 和 on_pre_enter() 有什么区别?
    • 顺便说一下,我刚刚测试了它,它没有工作。与 'super' 相同的 AttributeError
    • 请参考我更新后的说明和解决方案。
    • @Artemyx 小部件引用已经正确,无需更改引用小部件的方式。只需按照建议将 id 更改为非字符串即可。
    猜你喜欢
    • 2016-05-01
    • 1970-01-01
    • 2016-08-09
    • 1970-01-01
    • 1970-01-01
    • 2021-04-20
    • 1970-01-01
    • 2019-07-17
    • 1970-01-01
    相关资源
    最近更新 更多