Velidan Velidan - 4 months ago 14
Python Question

Kivy kv file is not working

I have the same issue like described in this theme kv incorrect. When I use Builder and load the kv file I have normal working app. But when I try to use autoload kv file I have only black screen. Could someone explain me why? Thanks for any help.

My code. main.py

import kivy
kivy.require('1.9.1') # replace with your current kivy version !

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


class MainScreen(Screen):
pass


class AnotherScreen(Screen):
pass


class ScreenManagement(ScreenManager):
pass


class Test(App):

def build(self):
return ScreenManagement()

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


kv file. test.kv

#:kivy 1.9.1

#: import FadeTransition kivy.uix.screenmanager.FadeTransition

ScreenManagement:
transition: FadeTransition()
MainScreen:
AnotherScreen:

<MainScreen>:
name: "main"
Button:
on_release: app.root.current = "other"
text: "Next Screen"
font_size: 50

<AnotherScreen>:
name: "other"
Button:
on_release: app.root.current = "main"
text: "Prev Screen"
font_size: 50

Answer

In your kv file, you define ScreenManagement to be the root element with its associated screens. But in build, you return a newly created ScreenManagement object, which will not have any children defined.

Solution: Define build as

def build(self):
    pass

or change the definition of ScreenManagement in the kv file to

<ScreenManagement>:
    transition: FadeTransition()
    MainScreen:
    AnotherScreen:

so this will apply to all new ScreenManagement objects.