Search code examples
pythoninheritancekivy

Process data after the kv file is loaded


The problem

The RefreshLabel() method should be executed right after the rendering of the window

Need to be able to initialize variables or perform other operations that need to be done after the kv file has been read so I can connect to databases or other external resources. - In other words; the user should never be able to read the words Text NOT updated

rendered updated window of the kivy program


Simplified code

main.py

import kivy
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.properties import ObjectProperty

class MyGrid(GridLayout):
    my_label = ObjectProperty(None)

    def RefreshLabel(self):
        self.my_label.text = "Text updated"

class designApp(App):
    def build(self):
        return MyGrid()

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

design.kv

<MyGrid>
    cols:1
    size: root.width, root.height

    my_label: my_label

    Label:
        id: my_label
        text: "Text NOT updated"

    Button:
        text: "Update text"
        on_press: root.RefreshLabel()

Solution

  • Try using on_kv_post:

    class MyGrid(GridLayout):
        my_label = ObjectProperty(None)
    
        def on_kv_post(self, base_widget):
            self.my_label.text = "Text updated"