简体   繁体   English

.kv文件似乎不起作用

[英].kv file doesn't seem to work

So I'm just working with some example Kivy file code, and I came across this code which allows the user to switch between screens: 所以我只是使用一些示例Kivy文件代码,我遇到了这个允许用户在屏幕之间切换的代码:

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

Builder.load_string("""
<MenuScreen>:
    BoxLayout:
        Button:
            text: 'Build Scenario'
            on_press: root.manager.current = 'settings'
        Button:
            text: 'Run Existing Scenerio'

<SettingsScreen>:
    BoxLayout:
        Button:
            text: 'Run Existing Scenerio'
        Button:
            text: 'Back to menu'
            on_press: root.manager.current = 'menu'
""")

# Declare both screens
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()

I wondered to myself if it would be possible to put the code given in the Builder.load_string() method into a separate .kv file. 我想知道是否可以将Builder.load_string()方法中给出的代码放入单独的.kv文件中。 So I did just that. 所以我做到了。 I commented the Builder part out (I admit I don't know what its role is) and copied the string into a .kv file which looks like this: 我评论了Builder部分(我承认我不知道它的作用是什么)并将字符串复制到.kv文件中,如下所示:

 # the file name is test.kv
 #:kivy 1.0.9

<MenuScreen>:
    BoxLayout:
        Button:
            text: 'Build Scenario'
            on_press: root.manager.current = 'settings'
        Button:
            text: 'Run Existing Scenerio'

<SettingsScreen>:
    BoxLayout:
        Button:
            text: 'Run Existing Scenerio'
        Button:
            text: 'Back to menu'
            on_press: root.manager.current = 'menu'

Unfortunately when I run the code now I just get a black screen. 不幸的是,当我运行代码时,我只是得到一个黑屏。 Can anyone tell me what's wrong? 谁能告诉我什么是错的? Thanks! 谢谢!

The code creates the screenmanager ( sm ) in the main body of the python file. 代码在python文件的主体中创建screenmanager( sm )。 When the kv is loaded from a file this only happens later, so none of the kv rules are applied to sm . 当从文件加载kv时,这仅在稍后发生,因此没有kv规则应用于sm It was okay before because the load_string happens before it is instantiated. 之前没关系,因为load_string在实例化之前就已经发生了。

For this reason, instantiating widgets this way is bad practice, and the sm = ScreenManager(... etc should be moved to the build method. This is run after the kv file is loaded, so everything should work. 出于这个原因,以这种方式实例化小部件是不好的做法,并且sm = ScreenManager(...等应该被移动到构建方法。这是在加载kv文件之后运行的,所以一切都应该工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM