gpt4 book ai didi

python - Kivy kv 文件的行为与 Builder.load_string 不同

转载 作者:行者123 更新时间:2023-12-02 21:11:01 25 4
gpt4 key购买 nike

我正在尝试在 kivy 上实现一个 2 屏幕应用程序。我遵循了他们的示例,如果在 main.py 中调用“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'

最佳答案

kv 文件由 App 类在调用 run 时加载,但在 build 方法之前。您在此之前实例化您的小部件(在 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

关于python - Kivy kv 文件的行为与 Builder.load_string 不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33461543/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com