Kivy How to create widgets from dictionary in kivy

Viewed 940

I am new to the library kivy for Python. I found the additional library kivy-md which has very good looking ui elements. At the moment I want to create many MDTextField widgets from a dictionary variable e.g.

# 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",
    }
}

From this variable, I want to create widgets in the kv file that look like

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"])

I see two challenges in this problem that I am not able to solve. The first is how to parse the id values from the dictionary strings and the second problem is that I do not know how to loop over kivy widgets in a kv file.

Is there a way to achieve what I want?

1 Answers

Please note there are no attributes, self and key in KivyMD MDTextField. In the example, we use nested for loop to access the dictionary, text_fields.py

Example

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()

Output

Img01

Related