Kivy如何从字典中创建字典中的小部件

时间:2018-08-24 20:17:35

标签: python kivy dry

我是Python库的新手。我发现附加的kivy-md库具有很好的ui元素。目前,我想根据字典变量创建许多MDTextField小部件,例如

# text_fields.py
text_fields = {
    "text_field1": {
        "key": 0,
        "self": "text_field1",
        "hint_text": "Textfield 1",
        "helper_text": "This is textfield 1",
    },

    "text_field2": {
        "key": 1,
        "self": "text_field2",
        "hint_text": "Textfield 2",
        "helper_text": "This is textfield 2",
    }
}

从这个变量中,我想在kv文件中创建看起来像

的小部件
GridLayout:
    MDTextField:
        id: text_field1
        hint_text: text_fields["text_field1"]["hint_text"]
        helper_text: text_fields["text_field1"]["helper_text"]
        helper_text_mode: "on_focus"
        on_text_validate: app.on_text_validate(text_fields["text_field1"]["self"])
    MDTextField:
        id: text_field2
        hint_text: text_fields["text_field2"]["hint_text"]
        helper_text: text_fields["text_field2"]["helper_text"]
        helper_text_mode: "on_focus"
        on_text_validate: app.on_text_validate(text_fields["text_field2"]["self"])

我看到这个问题无法解决的两个挑战。第一个是如何从字典字符串中解析id值,第二个问题是我不知道如何在kv文件中循环显示kivy小部件。

有没有办法实现我想要的?

1 个答案:

答案 0 :(得分:2)

请注意,KivyMD MDTextField中没有属性selfkey。在示例中,我们使用嵌套的for循环来访问字典text_fields.py

示例

main.py

from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivymd.textfields import MDTextField
from kivymd.theming import ThemeManager
from text_fields import text_fields
from functools import partial


class RootWidget(GridLayout):

    def __init__(self, **kwargs):
        super(RootWidget, self).__init__(**kwargs)
        self.cols = 1
        app = App.get_running_app()
        for key, fields in text_fields.items():
            mdt = MDTextField(id=key, helper_text_mode="on_focus")
            for subfield, value in fields.items():
                mdt.subfield = str(value)
            mdt.bind(on_text_validate=partial(app.on_text_validate, text_fields[key]["self"]))
            self.add_widget(mdt)


class MainApp(App):
    title = "KivyMD MDTextField Demo"
    theme_cls = ThemeManager()

    def build(self):
        return RootWidget()

    def on_text_validate(self, value, obj):
        print("\napp.on_text_validate:")
        print("\tobj=", obj)
        print("\tvalue=", value)
        print("\tobj.text=", obj.text)


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

输出

Img01