Understand bind in kivy

Viewed 178

I want to understand more about the bind method

I can't figure out, why that code doesn't work, (I reduce my problem to this, to help me understand the reason), thank you so much for your time

from kivy.app import App
from kivy.uix.gridlayout import GridLayout


class Game(GridLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.a = 0

        self.bind(a=self.f)

    def f(self, *args):
        print("ok")


class TestApp(App):
    def build(self):
        self.game = Game()
        return self.game


if __name__ == "__main__":
    TestApp().run()
Traceback (most recent call last):
    File "test2.py", line 23, in <module>
        TestApp().run()
    File "C:\Users\Legion\AppData\Local\Programs\Python\Python37-32\lib\site-packages\kivy\app.py", line 829, in run
        root = self.build()
    File "test2.py", line 18, in build
        self.game = Game()
    File "test2.py", line 10, in __init__
        self.bind(a=self.f)
    File "kivy\_event.pyx", line 427, in kivy._event.EventDispatcher.bind
KeyError: 'a'
1 Answers

If the docs are reviewed:

bind(**kwargs)
Bind an event type or a property to a callback

(emphasis added)

As noted, it is indicated by property that is different from attributes of the class.

So using your code as a base and adding the functionality to change the value every second:

from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.properties import NumericProperty
from kivy.clock import Clock

class Game(GridLayout):
    a = NumericProperty(0)

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.bind(a=self.f)

    def f(self, *args):
        print("ok")


class TestApp(App):
    def build(self):
        Clock.schedule_interval(self.foo, 1)
        self.game = Game()
        return self.game

    def foo(self, dt):
        self.game.a += 1


if __name__ == "__main__":
    TestApp().run()

And why are Properties used?

Because that type of properties store the associated callbacks (for example in the example the callable f) and then when its value changes invoke all the callbacks with which it has a binding.

Related