如果要将回调附加到kivywidget,例如textinput,可以使用bind()函数。来自Kivy docs的textinput示例:
def on_text(instance, value):
print('The widget', instance, 'have:', value)
textinput = TextInput()
textinput.bind(text=on_text)
但是如何将它附加到kvlang文件中创建的元素?
答案 0 :(得分:2)
获取元素的引用,然后正常调用bind
。例如,对于应用程序的根小部件,您可以使用App.get_running_app().root.bind
,或者对于其他人,您可以通过kv ID导航小部件树。
答案 1 :(得分:0)
您可以在bind()
引用的小部件上调用self.ids['id_from_kvlang']
。但是,这不能在类级别上完成,您需要在实例上进行操作。所以你需要将它放在类的函数中。
在对象实例化时调用__init__
函数,以便将其放在那里。但是你需要安排它,所以它不会立即发生,你绑定的小部件还没有,所以你必须等待一个框架。
class SomeScreen(Screen):
def __init__(self,**kwargs):
#execute the normal __init__ from the parent
super().__init__(**kwargs)
#the callback function that will be used
def on_text(instance, value):
print('The widget', instance, 'have:', value)
#wrap the binding in a function to be able to schedule it
def bind_to_text_event(*args):
self.ids['id_from_kvlang'].bind(text=update_price)
#now schedule the binding
Clock.schedule_once(bind_to_text_event)