在单独的.kv(Kivy)文件中定义的屏幕之间切换

时间:2018-07-22 20:40:46

标签: python kivy screen

我曾经设法通过在单个.kv文件中定义所有内容(包括屏幕)来使多屏幕程序正常工作。

通过使用import(在.kv文件中)或root.current(在Python文件中),我可以在屏幕之间进行切换。但是,一旦有多个窗口和许多小部件,.kv文件就会变得非常大且难以维护。

这一次,我试图在单独的.kv文件中定义屏幕,但是我无法在屏幕之间切换来工作。到目前为止,每次尝试都导致错误(语法无效,屏幕名称未定义...)。

是否有一种或多种在不同的.kv文件中定义的屏幕之间切换的方法? 这是我正在使用的文件:

main.py

self.root.current

main.kv:

from kivy.app import App


class MainApp(App):
    pass


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

screen_1.kv:

#:include screen_1.kv
#:include screen_2.kv

#:import NoTransition kivy.uix.screenmanager.NoTransition

ScreenManager:
    transition: NoTransition()


    Screen:
        name: "main_screen"

        BoxLayout:
            orientation: "vertical"

            Label:
                text: "main screen"
            Button:
                text: "to screen 1"
                on_press: app.root.current = "screen_1"
            Button:
                text: "to screen 2"
                on_press: app.root.current = "screen_2"

screen_2.kv:

Screen:
    name: 'screen_1'

    BoxLayout:
        orientation: "vertical"

        Label:
            text: "Screen 1"
        Button:
            text: "to main screen"
            on_press: app.root.current = "main_screen"
        Button:
            text: "to screen 2"
            on_press: app.root.current = "screen_2"

1 个答案:

答案 0 :(得分:0)

解决方案

  1. dynamic class添加到screen_1.kvscreen_2.kv中,例如分别为<Screen1@Screen>:<Screen2@Screen>:
  2. 实例化Screen1:中的Screen2:main.kv屏幕

示例

screen_1.kv

<Screen1@Screen>:
    name: 'screen_1'

    BoxLayout:
        orientation: "vertical"

        Label:
            text: "Screen 1"
        Button:
            text: "to main screen"
            on_press: app.root.current = "main_screen"
        Button:
            text: "to screen 2"
            on_press: app.root.current = "screen_2"

screen_2.kv

<Screen2@Screen>:
    name: 'screen_2'

    BoxLayout:
        orientation: "vertical"

        Label:
            text: "Screen 2"
        Button:
            text: "to main screen"
            on_press: app.root.current = "main_screen"
        Button:
            text: "to screen 1"
            on_press: app.root.current = "screen_1"

main.kv

#:include screen_1.kv
#:include screen_2.kv

#:import NoTransition kivy.uix.screenmanager.NoTransition


ScreenManager:
    transition: NoTransition()


    Screen:
        name: "main_screen"

        BoxLayout:
            orientation: "vertical"

            Label:
                text: "main screen"
            Button:
                text: "to screen 1"
                on_press: app.root.current = "screen_1"
            Button:
                text: "to screen 2"
                on_press: app.root.current = "screen_2"

    Screen1:

    Screen2:

输出

Img01 - Main Screen Img02 - Screen1 Img03 - Screen2