Search code examples
pythonkivykivymd

Initializing KivyMD App object before loading root widget problem


I am tinkering around with multiple screens in KivyMD but I´m stuck with this problem:

ValueError: KivyMD: App object must be initialized before loading root widget

The thing is that it only pops out when I try to use a KivyMD widget like in the code below. But if I change those KivyMD widgets with the ones that come with the original kivy library (say replacing a MDLabel with Label) it seems to execute with no problems.

It obviously seems that I'm missing something but I can't figure out what. So I'll apreciate any help from you.

Thanks for your attention

python file:

import kivy
from kivymd.app import MDApp
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen

class MainScreen(Screen):
    pass

class DateScreen(Screen):
    pass

class ActivityScreen(Screen):
    pass

class Manager(ScreenManager):
    pass

kv = Builder.load_file("layout2.kv")

class MainApp(MDApp):
    def build(self):
        self.theme_cls.theme_style = "Dark"
        return kv

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

kivy file:

Manager:
    MainScreen:
    DateScreen:
    ActivityScreen:

<MainScreen>:
    name: "main_screen"
    RelativeLayout:
        MDLabel:
            title: "Testing"

Solution

  • Just move the line:

    kv = Builder.load_file("layout2.kv")
    

    inside the build() method, like this:

    class MainApp(MDApp):
        def build(self):
            self.theme_cls.theme_style = "Dark"
            kv = Builder.load_file("layout2.kv")
            return kv