【问题标题】:Kivy: How to attach a callback to a widget created in kvlangKivy:如何将回调附加到在 kvlang 中创建的小部件
【发布时间】:2016-02-16 18:52:44
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: python kivy


    【解决方案1】:

    获取对元素的引用,然后照常调用bind。例如,对于应用程序的根小部件,您可以使用App.get_running_app().root.bind,或者对于其他应用,您可以通过 kv ids 导航小部件树。

    【讨论】:

    • 当我在课堂上调用self.ids['id_from_kvlang'].bind(text=on_text) 时,我得到了NameError: name 'self' is not defined,我可以理解,但我不知道如何正确操作。没有self. 我得到NameError: name 'ids' is not defined 或者我不应该从班级级别调用它吗?
    • 不要从类级别调用它 - 这是类定义,但您正在尝试与类的实例进行交互。
    • 啊好的,所以我已经把它放在 init 函数中了,但是你还需要稍微延迟一下,因为小部件还不存在第一刻。我将在新答案中重写文档中的示例以供将来参考。感谢您的帮助!
    【解决方案2】:

    您可以在self.ids['id_from_kvlang'] 引用的小部件上调用bind()。但是这不能在类级别上完成,您需要在实例上进行操作。所以你需要把它放在类的一个函数中。

    __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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多