简体   繁体   中英

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

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.

you can also add:

from kivy.properties import ObjectProperty

then change:

class ScreenManagement(ScreenManager):
    pass

to this:

class ScreenManagement(screenManager):
    mainscreen = ObjectProperty(None)
    anotherscreen = ObjectProperty(None)

then in your .kv file you want to change this:

ScreenManagement:
    transition: FadeTransition()
    MainScreen:
    AnotherScreen:

to this:

<ScreenManagement>:
    transition: FadeTransition()
    mainscreen: mainscreen
    anotherscreen: anotherscreen

then for your MainScreen add and id like so:

<MainScreen>:
    id: mainscreen

and do the same for you AnotherScreen.

Check the version of your Python and the version of Pygame you're using. I got that problem and my issue came from the version of Pygame.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM