如何从 kivymd 中主 class 中的不同 class 访问 ID?

How to access ids from different class inside the main class in kivymd?

我为带有复选框的列表创建了自定义 classes,因此在 .kv 文件中,第二个 class 在第一个 class 中。在第二个 class 中我添加了一个 id: 所以我想通过 id:.

访问那个 class

第一个 class 是 MDList,第二个 class 是 MDCheckBox

class ListItemWithCheckbox(OneLineAvatarIconListItem):
    pass


class LeftCheckbox(ILeftBodyTouch, MDCheckbox):
    pass

.kv 文件:

        ListItemWithCheckbox:
            text: "List One"

            LeftCheckbox:
                id: 'id_one'
                group: 'group'

        ListItemWithCheckbox:
            text: "List Two"

            LeftCheckbox:
                id: 'id_two'
                group: 'group'

所以,现在我想在主 Class 中的自定义函数中访问这些 ID id_oneid_two 检查这些复选框何时处于活动状态。

像这样:

class MainApp(MDApp):
    def custom(self):
        id1 = LeftCheckbox.ids.id_one
        id2 = LeftCheckbox.ids.id_two

我是基维新人

有几件事,首先不要在 kv 文件中的 id 名称周围添加引号。

这些应该是

    ListItemWithCheckbox:
        text: "List One"

        LeftCheckbox:
            id: id_one
            group: 'group'

    ListItemWithCheckbox:
        text: "List Two"

        LeftCheckbox:
            id: id_two
            group: 'group'

通常,您访问 ID 的方式是使用小部件的 ID 属性。现在应用 class 没有 id 属性,因此您必须在调用 id 之前传递 root,即

class MainApp(App):
    def custom:
        self.root.ids['id_one']  # Accesses the widget with the id of id_one
        self.root.ids['id_two']

小部件的 ID 是一个字典,键是您定义的 ID,值是小部件的 WeakProxy。

为了完成这里是一些示例代码:

from kivy.app import App
from kivy.lang import Builder

kv = Builder.load_string(
    """
BoxLayout:
    Button:
        id: button_one
        pos: 0, 0
        text: 'hello'
        on_release: app.custom()
            
"""
)


class MainApp(App):

    def build(self):
        return kv

    def custom(self):
        print(self.root.ids['button_one'])

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

按下按钮打印 <kivy.uix.button.Button object at 0x1098ea270>