Kivy Kv File Behaves Different from Builder. Load_String

I'm trying to implement a 2 screen app on kivy. I have followed their example and it works if "Builder.load_string" is called in main.py.

However, if I comment it out and create a .kv file, I just get a blank screen. What am I doing wrong?

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

#Builder.load_string("""
#<MainScreen>:
    #BoxLayout:
        #Button:
            #text: 'Goto settings'
            #on_press: root.manager.current = 'settings'
        #Button:
            #text: 'Quit'

#<SettingsScreen>:
    #BoxLayout:
        #Button:
            #text: 'My settings button'
        #Button:
            #text: 'Back to menu'
            #on_press: root.manager.current = 'main'
#""")

# Declare both screens
class MainScreen(Screen):
    pass

class SettingsScreen(Screen):
    pass

# Create the screen manager
sm = ScreenManager()
sm.add_widget(MainScreen(name='main'))
sm.add_widget(SettingsScreen(name='settings'))

class TestApp(App):

    def build(self):
        return sm

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

And here is testapp.kv

<MainScreen>:
    BoxLayout:
        Button:
            text: 'Goto settings'
            on_press: root.manager.current = 'settings'
        Button:
            text: 'Quit'

<SettingsScreen>:
    BoxLayout:
        Button:
            text: 'My settings button'
        Button:
            text: 'Back to menu'
            on_press: root.manager.current = 'main'

1 Answer

The kv file is loaded by the App class when run is called, but before the build method. You instantiate your widgets before this (above the App class declaration), so the kv rules haven't yet been loaded and do not apply. To fix it, move the instantiation to the build method.

Edit: Change:

# Create the screen manager
sm = ScreenManager()
sm.add_widget(MainScreen(name='main'))
sm.add_widget(SettingsScreen(name='settings'))

class TestApp(App):

    def build(self):
        return sm

to

class TestApp(App):

    def build(self):
        # Create the screen manager
        sm = ScreenManager()
        sm.add_widget(MainScreen(name='main'))
        sm.add_widget(SettingsScreen(name='settings'))
        return sm
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest