Kivy:如何将回调附加到在kvlang中创建的小部件 [英] Kivy: How to attach a callback to a widget created in kvlang

查看:131
本文介绍了Kivy:如何将回调附加到在kvlang中创建的小部件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您要将回调附加到kivywidget(例如textinput)时,可以使用bind()函数.来自 Kivy文档的示例,用于文本输入:

When you want to attach a callback to a kivywidget, for example a textinput you can use the bind() function. Example from Kivy docs for a textinput:

def on_text(instance, value):
    print('The widget', instance, 'have:', value)

textinput = TextInput()
textinput.bind(text=on_text)

但是如何将其附加到在kvlang文件中创建的元素上?

But how do I attach it to an element that was created in the kvlang file?

推荐答案

您可以在self.ids['id_from_kvlang']引用的小部件上调用bind().但是,这不能在类级别完成,您需要在实例上进行操作.因此,您需要将其放入类的函数中.

You can call the bind() on the widget referenced by self.ids['id_from_kvlang']. However this cannot be done on class level, you need to operate on the instance. So you need to put it in a function of the class.

__init__函数在对象的实例化时被调用,因此您可以将其放在那里.但是,您需要安排它,这样它不会立即发生,要绑定的小部件还不存在,因此您必须等待一帧.

The __init__ function is called at the instantiation of the object so you can put it there. However you need to schedule it, so it won't happen instantly, the widgets you are binding to are not there yet so you have to wait a frame.

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)

这篇关于Kivy:如何将回调附加到在kvlang中创建的小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆