【问题标题】:How to access ids from different class inside the main class in kivymd?如何访问kivymd主类中不同类的ID?
【发布时间】:2021-03-24 04:45:21
【问题描述】:

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

第一类是MDList,第二类是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'

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

类似这样的:

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

我是 kivy 的新手。

【问题讨论】:

    标签: python kivy kivymd


    【解决方案1】:

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

    这些应该是

        ListItemWithCheckbox:
            text: "List One"
    
            LeftCheckbox:
                id: id_one
                group: 'group'
    
        ListItemWithCheckbox:
            text: "List Two"
    
            LeftCheckbox:
                id: id_two
                group: 'group'
    

    通常,您访问 ID 的方式是使用小部件的 id 属性。现在 app 类没有 id 属性,所以你必须在调用 ids 之前传递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>

    【讨论】:

    • 我收到一个错误print(self.root.ids['id_one']) KeyError: 'id_one'
    • 我的错,我的问题是我在 kv 文件中的 id 名称周围添加了引号。现在它起作用了。
    猜你喜欢
    • 2020-04-08
    • 1970-01-01
    • 2015-07-24
    • 1970-01-01
    • 2017-03-05
    • 2011-10-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多