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()
This defines a new class dynamically, named
MyButton
, which has no relation to theMyButton
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 theBuilder.load_string
until after this class is declared - normally it's best to do this in the App'sbuild
method, as everything important is guaranteed to be initialised at this point.