【问题标题】:How to set id for widgets in kivy from python code file如何从python代码文件为kivy中的小部件设置id
【发布时间】:2021-09-24 15:12:49
【问题描述】:
class NavigationDrawer(MDApp):
def build(self):
    return Builder.load_string(KV)

def on_start(self):

    files=[{"price":"890" , "meter" : "36" , "elevator" : "True"}]

    for file in files:
        first_base_el = MDCard(size_hint=(1, None), size=(self.root.width,
              self.root.height / 4))
        second_base_el =BoxLayout(orientation='vertical')

        for element in file.keys() :

            external_el = MDRectangleFlatButton(
                    text=f'{element} : {file[element]}',
                    size_hint=(1, .2)
            )

            second_base_el.add_widget(external_el)

        first_base_el.add_widget(second_base_el)
        self.root.ids.container.add_widget(first_base_el)

我收到此错误:self.ids[element] = weakref.ref(external_el) AttributeError: 'NavigationDrawer' 对象没有属性 'ids'

【问题讨论】:

    标签: python kivy kivy-language kivymd


    【解决方案1】:

    从 python 代码分配的“id”不能作为 kivy lang 的“id”工作,引用从 python 代码添加的小部件的最佳方法是使用“children”或“parent”属性并获得正确小部件树中的小部件,并通过调用或对象使用它

    在您的示例中,“first_base_el”具有您添加的小部件,因此要获取您已经添加的小部件,您应该使用:

    B=first_base_el.children

    Card=B[0] #this 等于 "second_base_el" 小部件

    【讨论】:

      【解决方案2】:

      是的,这是因为不是在 self.root.ids.container.add_widget(first_base_el) 行中,self 指的是 AppClass,然后您正在访问本身就是 appclass 的根。

      AppClass 没有任何属性ids。只有小部件类才能访问 ids 属性

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-03-11
        • 1970-01-01
        • 2021-05-23
        • 1970-01-01
        • 2022-08-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多