当我把它放在外部.kv文件中时,为什么使用screenmanager的正确.kv代码无效?

时间:2014-04-06 20:47:24

标签: python kivy

功能完善的代码:

from kivy.app import App
from kivy.lang import Builder

from kivy.uix.screenmanager import ScreenManager, Screen, NoTransition

Builder.load_string("""
#:kivy 1.8

<StartScreen>:
    BoxLayout:
        Label:
            text: "Press Button to"
        Button:
            text: "Start Server"
            on_press:
                root.start_server()
                root.manager.current='stopscreen'

<StopScreen>:
    BoxLayout:
        Label:
            text: "Press Button to"
        Button:
            text: "Stop Server"
            on_press:
                root.stop_server()
                root.manager.current='startscreen'
""")

class StartScreen(Screen): 
    def start_server(self):
        print('Server started.')


class StopScreen(Screen):  
    def stop_server(self):
        print('Server stopped.')


sm = ScreenManager(transition=NoTransition())
sm.add_widget(StartScreen(name='startscreen'))
sm.add_widget(StopScreen(name='stopscreen'))


class MySpecialApp(App):

    def build(self):
        return sm


MySpecialApp().run()

现在,根据Kivy Docs,应该可以将在此代码开头加载的字符串放入外部文件myspecial.kv 一旦我这样做,我的屏幕留空,没有按钮,没有文字。为什么会这样,我怎样才能让它发挥作用?

2 个答案:

答案 0 :(得分:6)

应用程序启动时会加载myspecial.kv文件,但您会在此之前初始化您的小部件。在您运行sm = ScreenManager(transition=NoTransition())时,kv尚未加载,因此ScreenManager没有预期的样式。

您应该在build方法中创建小部件。在运行此方法之前加载了kv文件,因此一切都应该正常。

答案 1 :(得分:0)

<强> main.py

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


class StartScreen(Screen): 
    def start_server(self):
        print('Server started.')


class StopScreen(Screen):  
    def stop_server(self):
        print('Server stopped.')


class RootScreen(ScreenManager):
    pass


class MySpecialApp(App):
    def build(self):
        return RootScreen()


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

<强> myspecial.kv

<RootScreen>:
    StartScreen:
    StopScreen:


<StartScreen>:
    BoxLayout:
        Label:
            text: "Press Button to"
        Button:
            text: "Start Server"
            on_press:
                root.start_server()
                root.manager.current='stopscreen'


<StopScreen>:
    BoxLayout:
        Label:
            text: "Press Button to"
        Button:
            text: "Stop Server"
            on_press:
                root.stop_server()
                root.manager.current='startscreen'