Search code examples
pythonkivykivy-languagekivymd

Binding method to button - Kivy


Python Code:

class Test(MDApp):
    def build(self):
        return Builder.load_file('test.kv')
    def btn(self):
        print('Button Pressed')

kv code:

MDScreen:
    MDRaisedButton:
        text:'Submit'
        on_press: root.btn()

On pressing the Button, I'm receiving this error:

AttributeError: 'MDScreen' object has no attribute 'btn'

What am I doing wrong?

BTW, I am using kivymd which is a fork of kivy and works almost the same way.


Solution

  • on_press: root.btn()

    As the error says, root evaluates to your MdScreen instance, the root of the kv rule. You want app.btn().

    BTW, I am using kivymd which is a fork of kivy and works almost the same way.

    KivyMD is not a fork of Kivy, it's a module that depends on Kivy.