2015-11-01 54 views
0

我試圖在kivy上實現2屏幕應用程序。我遵循他們的例子,如果在main.py中調用「Builder.load_string」,它就會起作用。Kivy kv文件的行爲與Builder.load_string不同

但是,如果我將它註釋掉並創建一個.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

千伏文件是由應用程序加載的類在運行時被調用,但構建方法之前。您在此之前(在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