簡體   English   中英

Kivy:如何將回調附加到在kvlang中創建的小部件

[英]Kivy: How to attach a callback to a widget created in kvlang

如果要將回調附加到kivywidget,例如textinput,則可以使用bind()函數。 來自Kivy文檔的文本輸入示例:

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

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

但是,如何將其附加到在kvlang文件中創建的元素上?

獲取對該元素的引用,然后照常調用bind 例如,對於應用程序的根窗口小部件,您可以使用App.get_running_app().root.bind ;對於其他應用程序,則可以通過kv id瀏覽窗口小部件樹。

您可以在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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM