我想了解有关绑定(bind)方法的更多信息
我不明白为什么该代码不起作用,(我将我的问题简化为这个,以帮助我理解原因),非常感谢您的时间
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'
最佳答案
如果docs已审核:
bind(**kwargs)
Bind an event type or a property to a callback
(已添加强调)
如上所述,它由与类的属性不同的属性表示。
因此,使用您的代码作为基础并添加每秒更改值的功能:
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()
<小时/>
为什么是 Properties使用过吗?
因为该类型的属性存储关联的回调(例如示例中的可调用 f
),然后当其值更改时调用与其绑定(bind)的所有回调。
关于python - 了解 kivy 中的绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56718648/