你如何在 Kivy 中的屏幕之间传递变量?

How do you pass a variable between screens in Kivy?

这是我的代码:

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


build = f"""
WindowManager:
    ScreenOne:

<ScreenOne>:
    name: 'one'

    BoxLayout:
        orientation: 'horizontal'
        size: root.width, root.height

        Button:
            text: 'Load Screen Two'
            on_release:
                app.root.load_screen_two('Screen Two')
                app.root.current = 'two'


<ScreenTwo>:
    name: 'two'

    BoxLayout:
        orientation: 'horizontal'
        size: root.width, root.height

        Label:
            text: root.text
"""


class ScreenOne(Screen):
    pass


class ScreenTwo(Screen):
    def __init__(self, text, **kw):
        super().__init__(**kw)
        self.text = text


class WindowManager(ScreenManager):
    def load_screen_two(self, text):
        self.add_widget(ScreenTwo(text))


class Application(App):
    def build(self):
        return Builder.load_string(build)


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

我正在尝试通过单击另一个屏幕中的按钮来实例化一个新屏幕。这本身就完美无缺!我正在尝试做的另一件事是将一个变量传递给该屏幕,以便与我稍后将要编写的方法一起使用。在此示例中,我只是传递一个字符串。每当我尝试 运行 时,单击屏幕一中的按钮后,我都会收到以下错误:AttributeError: 'ScreenTwo' object has no attribute 'text'

我怎样才能解决这个问题并成功地在屏幕之间传递变量?

为属性 text 创建一个 StringProperty 并将其作为 kwarg 传递给 ScreenTwo

class ScreenTwo(Screen):
    text = StringProperty("")


class WindowManager(ScreenManager):
    def load_screen_two(self, text):
        self.add_widget(ScreenTwo(text = text))

但是,下面是输入错误还是原始代码中确实存在?如果这里是后者,那么缩进应该是一致的。

        Button:
            text: 'Load Screen Two'
            on_release:
                on_press: app.root.load_screen_two('Screen Two')
                on_release: Factory.NewGame().open()
                app.root.current = 'two'