如何将复杂对象传递到 kv 文件中?

How can you pass a complex object into a kv file?

我正在构建一个游戏,整个游戏逻辑包含在 Game() class 中。我想将这个游戏的对象传递到 kv 文件中。这是我的代码:

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


class Game():
    name = "Game Name"

    def __init__(self, player):
        self.player = player


build = """
WindowManager:
    HomeScreen:


<HomeScreen>:
    name: 'home'

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

        Button:
            text: "New Game"
            on_release:
                app.root.load_game("player")
                app.root.current = 'game'


<GameScreen>:
    name: 'game'

    BoxLayout:
        orientation: 'horizontal'

        Label:
            text: root.game.name
"""


class HomeScreen(Screen):
    pass


class GameScreen(Screen):
    player = StringProperty()

    def __init__(self, player, **kw):
        super().__init__(**kw)
        self.player = player
        self.game = Game(self.player)


class WindowManager(ScreenManager):
    def load_game(self, player):
        self.add_widget(GameScreen(player))


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


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

这可以运行,但是当我尝试单击按钮以实例化游戏屏幕时,它会抛出一个错误,指出 GameScreen 没有“游戏”属性。据我所知,Kivy 中没有 ClassProperty 属性,我如何传入一个不是原始类型的对象?

将对象添加为 属性:

from kivy.properties import StringProperty, ObjectProperty # Import ObjectProperty


class GameScreen(Screen):
    player = StringProperty() 
    game = ObjectProperty(Game) #Add an object property