简体   繁体   中英

Attribute error with super in Kivy/Python

Here is the exerpt of my code on the .py side that cause the problem:

class ScreenMath(Screen):

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

And the .kv side:

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

When I run the code, an AttributeError occurs :

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

As you saw, I want to change the text of my value (3 will later be a variable) when the screen in initiated, but maybe there is a better way to do that.

Problem - AttributeError

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

Root Cause

Kivy was not able to find the attribute because the id s in your kv file were assigned string values.

Solution

The following changes are required to solve the problem.

  1. id s in kv file are not string. Therefore, remove double quote from id .
  2. Replace self.ids.anchmath.ids.grdmath.ids.score.text with 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)) 

Snippet - Python code

class ScreenMath(Screen):

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

Snippet- kv file

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

Output

图01

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM