Classes with kivy layout

334 views Asked by At

I wish to define a widget using the kivy language, but then I want to add functions to the class. Below is my naive attempt, which fails when I click the button with the message "AttributeError: 'MyButton' object has no attribute 'second_pressed'"
How do I make a class with functions and a kivy language defined look?

import sys
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout

root = Builder.load_string('''
BoxLayout:
    Label:
        text: 'hello'
    MyButton:

<MyButton@Button>:
    text: 'Second button'
    on_press: self.second_pressed()
''')

class MyButton():
    def second_pressed():
        print "second pressed"
        sys.stdout.flush()

class Tryit(App):
    def build(self):
        return root

if __name__ == '__main__':
    Tryit().run()
1

There are 1 answers

0
inclement On BEST ANSWER
<MyButton@Button>:

This defines a new class dynamically, named MyButton, which has no relation to the MyButton in your python code for which you added that method.

To get it to work, instead write just <MyButton>:, which denotes a rule for an existing class. You may also need to delay the Builder.load_string until after this class is declared - normally it's best to do this in the App's build method, as everything important is guaranteed to be initialised at this point.