屏幕管理器在kivy与kv文件

时间:2017-12-24 18:43:24

标签: python kivy

这是我发布的第一个问题,如果问题没有完成,那就很抱歉。

我在kivy的屏幕管理器官方页面上尝试了这个例子,但是如果我尝试使用kv文件而不是Builder,我会得到一个黑页。

Test.py

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

class MenuScreen(Screen):
    pass

class SettingsScreen(Screen):
    pass

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

class TestApp(App):

    def build(self):
        return sm

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

Test.kv

<MenuScreen>:
    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 = 'menu'

1 个答案:

答案 0 :(得分:0)

您的test.py应如下所示:

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

# Declare both screens
class MenuScreen(Screen):
    pass

class SettingsScreen(Screen):
    pass

class TestApp(App):
    pass

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

你的test.kv文件应该是:

#: kivy 1.10.0

ScreenManager:
    id: screen_manager
    MenuScreen:
        id: menu_screen
        name: 'menu'
        manager: 'screen_manager'
    SettingsScreen:
        id: settings_screen
        name: 'settings'
        manager: 'screen_manager'

<MenuScreen>:
    BoxLayout:
        Button:
            text: 'Goto settings'
            on_press: app.root.current = 'settings'
        Button:
            text: 'Quit'

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