Kivy:如何通过id获取widget(不带kv)

2024-04-25 16:51:40 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我在Kivy中动态地定义一些小部件(按钮)并动态地分配它们的id。 在这个用例中我没有使用kv语言。 我可以在不跟踪小部件本身的情况下保留小部件I d的引用:然后我想通过它的id访问小部件。 我能做点像“按id获取小部件”这样的事情吗? (如果我在kv文件中定义了小部件,我可以使用self.id.the_widget_id通过其id访问小部件本身)


Tags: 文件theself语言id定义部件情况
3条回答

Kivy小部件构成树结构。任何小部件的子部件都可以通过childrenatribute使用。如果需要,可以只保留对根窗口的引用,然后使用walk方法在其小部件上迭代:

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

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

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

您可以直接使用id检索小部件。例如,在代码中,可以使用以下代码段修改按钮文本:

self.ids.2.ids.3.ids.1.text = '!!!!'

您可以使用id更改每个小部件的属性:

self.ids['order_number'].text='S1212'

相关问题 更多 >

    热门问题