即使在kv文件中设置了AccordionItem title属性为空?

时间:2017-07-17 12:34:17

标签: python kivy kivy-language

我试图在python代码中访问AccordionItem的title属性,这是在kv文件中设置的。该属性为空字符串,即使它在GUI中正确显示。

有没有办法获取此属性的值,或者我在这里遗漏了什么?

kv文件

$rows = [];
if ($result->num_rows) 
  while($row = $result->fetch_assoc()) $rows[] = $row; // append to array
echo "<script> var objArray = " . json_encode($rows) . "; </script>";

python代码

<TableModifications>:
    accordion: accordion
    MDAccordion:
        id: accordion
        orientation: 'vertical'
        size_hint_x: None
        width: '240dp'
        TableAccordionItem:
            title:'Add' # I want to access this in python code
            icon: 'plus'
        TableAccordionItem:
            title:'Edit'
            icon: 'pencil'
        TableAccordionItem:
            title:'Remove'
            icon: 'delete'

1 个答案:

答案 0 :(得分:0)

你需要使用kivy的ObjectProperty,它会神奇地绑定到你的kv中的小部件。此外,如果窗口小部件已经在kv lang中添加到窗口小部件树中,那么您不需要在python中再次添加该窗口小部件。 add_widget不是您需要覆盖的方法。如果您要添加小部件,请执行以下操作:self.add_widget(Label(text="Hello"))

示例:

from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.properties import ObjectProperty
from kivy.app import App
from kivy.lang import Builder

Builder.load_string("""
<RootWidget>:
    accord_1: accord_1
    accord_2: accord_2
    accord_3: accord_3
    Accordion:
        orientation: "vertical"
        AccordionItem:
            id: accord_1
            title: "Title 1"
            Label:
                text: "Accordion One Content."
        AccordionItem:
            id: accord_2
            title: "Title 2"
            Label:
                text: "Accordion Two Content."
        AccordionItem:
            id: accord_3
            title: "Title 3"
""")


class RootWidget(BoxLayout):

    accord_1 = ObjectProperty(None)
    accord_2 = ObjectProperty(None)
    accord_3 = ObjectProperty(None)

    def __init__(self, *args, **kwargs):
        super(RootWidget, self).__init__(*args, **kwargs)

        self.accord_3.add_widget(Label(text="Accordion Three Content."))

        for ac in [self.accord_1, self.accord_2, self.accord_3]:
            print ac.title


class TestApp(App):
    def build(self):
        return RootWidget()


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