每次进入游戏画面时如何添加小部件?

时间:2016-04-20 16:39:02

标签: python widget screen kivy

我有一个FloatLayout" DiceMazeGame"包含我的游戏。

我有两个屏幕(菜单和游戏),我想在每次输入时从菜单屏幕添加DiceMazeGame到游戏屏幕。

每次从菜单屏幕进入游戏屏幕时,游戏都需要重置。

main.py

class DiceMazeGame(FloatLayout):
     #init
     #some functions

class MenuScreen(Screen):
     pass

class GameScreen(Screen):
     pass

dicemaze.kv

ScreenManagement:
    id: screen_manager
    transition: NoTransition()
    MenuScreen:
        name:"menu"
    GameScreen:
        name:"game"

<MenuScreen>:
    Button:
        on_press: root.manager.current = "game"
        text: "Play !"

<DiceMazeGame>:
    # Widgets  

我的代码只将DiceMazeGame添加一次到屏幕上。每次进入游戏画面时如何添加?

class GameScreen(Screen):
    def __init__(self, **kwargs):
        super(GameScreen, self).__init__(**kwargs)
        self.on_pre_enter(self.clear_widgets())
        self.on_pre_enter(self.add_widget(DiceMazeGame()))

1 个答案:

答案 0 :(得分:0)

您需要覆盖on_pre_enter方法,而不是在init中使用它一次

class GameScreen(Screen):

    # overwrite on_pre_enter method
    def on_pre_enter(self):
        self.add_widget(DiceMazeGame())

    # overwrite on_leave method - optional
    def on_leave(self):
        self.clear_widgets()