在 TabbedPanel 中获取 widget/item 个 ID

Getting widget/item ids within TabbedPanel

我在 Kivy 中创建了一个简单的应用程序,它有选项卡,在每个选项卡中我只有几个小部件。在添加 tabbedPanel 之前,我可以通过 "ids" 访问每个小部件。例如:

app.root.ids.mylabel1.ids.mylabel2.content

但是,现在我已经在 tabbedPanel 中添加了小部件,我无法访问它们。 tabbedPanel "blocks" 我不包含任何 ID:例如我的 .kv 文件有一个按钮:

<SelectableButton>:
    text: self.button_text
    id: SelectableButton_id
    canvas.before:
        Color:
            rgba: (0, 0.517, 0.705, 1) if self.selected else (0, 0.517, 0.705, 1)
        Rectangle:
            pos: self.pos
            size: self.size
    state: self.btnState
    on_release:
        print(app.root.content.ids)

returns 一个空字典。我遵循了 tabbedPanel 的指导,发现它只有一个 "children",即“.content”。但是我仍然无法访问此选项卡中的任何小部件。

我是不是走错了路?或者谁能​​指导我如何访问特定选项卡中的小部件。

使用 Kivy TabbedPanel,您可以使用 app.root.ids.id-nameself.ids.id-name 引用 ids,例如app.root.ids.label3.textself.ids.label3.text 因为当你的 kv 文件被解析时,kivy 会收集所有标记有 id's 的小部件,并将它们放在这个 self.ids 字典类型中 属性。

例子

main.py

from kivy.app import App
from kivy.uix.tabbedpanel import TabbedPanel
from kivy.lang import Builder
from kivy.uix.label import Label
from kivy.uix.button import Button

Builder.load_string("""

<Test>:
    size_hint: .5, .5
    pos_hint: {'center_x': .5, 'center_y': .5}
    do_default_tab: False

    TabbedPanelItem:
        text: 'first tab'
        Label:
            text: 'First tab content area'

    TabbedPanelItem:
        id: tab2
        text: 'tab2'

        BoxLayout:
            id: box1
            orientation: 'vertical'

            Label:
                id: label1
                text: 'Second tab content area'
            Button:
                id: button1
                text: 'Button that does nothing'

            BoxLayout:
                id: box2
                orientation: 'vertical'

                Label:
                    id: label2
                    text: 'Label 2'

                BoxLayout:
                    id: box3
                    orientation: 'vertical'

                    Button:
                        id: button2
                        text: 'Button 2'
                    Label:
                        id: label3
                        text: 'Label 3'

    TabbedPanelItem:
        text: 'tab3'
        RstDocument:
            text:
                '\n'.join(("Hello world", "-----------",
                "You are in the third tab."))

""")


class Test(TabbedPanel):

    def __init__(self, **kwargs):
        super(Test, self).__init__(**kwargs)
        print(f"\nself.ids.items():")
        for key, val in self.ids.items():
            if isinstance(val, Label) or isinstance(val, Button):
                print(f"\tkey={key}, val={val}, val.text={val.text}")
            else:
                print(f"\n\tkey={key}, val={val}")

        print(f"\nself.ids.label3.text={self.ids.label3.text}")


class TabbedPanelApp(App):
    def build(self):
        return Test()


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

输出