我试图在kivy上实现2屏应用。我已经按照他们的例子进行了操作,如果" Builder.load_string"在main.py中调用。
但是,如果我将其注释掉并创建.kv文件,我只会得到一个空白屏幕。我做错了什么?
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()
这是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'
答案 0 :(得分:1)
在调用run时,但在构建方法之前,App类会加载kv文件。您在此之前(在App类声明之上)实例化您的小部件,因此kv规则尚未加载且不适用。要修复它,请将实例化移动到构建方法。
编辑:更改:
# 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
到
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