Kivy:如何通过ID获取小部件(无kv) [英] Kivy : how to get widget by id (without kv)

查看:96
本文介绍了Kivy:如何通过ID获取小部件(无kv)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在Kivy中动态定义了一些小部件(按钮)并动态分配了它们的ID. 在这种用例中,我没有使用kv语言. 我可以保留对小部件ID的引用,而不必跟踪小部件本身:然后,我想通过其ID访问小部件. 我可以做类似通过id获取小部件"的事情吗? (如果我在kv文件中定义了窗口小部件,则可以使用self.ids.the_widget_id通过其ID访问窗口小部件本身)

Let's say I define on the fly in Kivy a few widgets (buttons) and dynamically assign their id. I'm not using kv language in this use case. I can keep a reference of a widget id without keeping track of the widget itself : then I'd like to access the widget through its id. Can I do something like "get widget by id" ? (If I had defined the widget in a kv file, I could have used self.ids.the_widget_id to access the widget itself through its id)

推荐答案

Kivy小部件可以树状结构.任何小部件的子级都可以通过children属性获得.如果需要,您可以仅保留对根窗口的引用,然后使用walk方法遍历其窗口小部件:

Kivy widgets make tree structure. Children of any widget are avaiable through children atribute. If you want, you can keep reference only to root window and then iterate over it's widgets using walk method:

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button 

class MyWidget(BoxLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        button = Button(text="...", id="1")
        button.bind(on_release=self.print_label)

        l1 = BoxLayout(id="2")
        l2 = BoxLayout(id="3")

        self.add_widget(l1)
        l1.add_widget(l2)             
        l2.add_widget(button)

    def print_label(self, *args):
        for widget in self.walk():
            print("{} -> {}".format(widget, widget.id))

class MyApp(App):
    def build(self):
        return MyWidget()

if __name__ == '__main__':
    MyApp().run()

walk()walk_reverse()方法已添加到1.8.1版本的Kivy中的kivy.uix.widget.Widget中.对于较旧的版本,您需要自己递归解析树:

walk() and walk_reverse() method were added to kivy.uix.widget.Widget in 1.8.1 version of Kivy. For older versions you need to recursively parse tree yourself:

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button 

class MyWidget(BoxLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        button = Button(text="...", id="1")
        button.bind(on_release=self.print_label)

        l1 = BoxLayout(id="2")
        l2 = BoxLayout(id="3")

        self.add_widget(l1)
        l1.add_widget(l2)             
        l2.add_widget(button)

    def print_label(self, *args):
        children = self.children[:]
        while children:
            child = children.pop()
            print("{} -> {}".format(child, child.id))
            children.extend(child.children)

class MyApp(App):
    def build(self):
        return MyWidget()

if __name__ == '__main__':
    MyApp().run()

这篇关于Kivy:如何通过ID获取小部件(无kv)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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