Kivy:dismiss()不适用于我的ModalView小部件

时间:2017-04-13 07:19:49

标签: python kivy kivy-language

我正在创建一个ModalView小部件并尝试通过按下它来关闭它。按下按钮的回调转到假设关闭它的方法。

这是main.kv:

<MainFrame>:
    id: main_frame
    ScreenMaster:
        id: screen_master
        StartScreen:
            id: start_screen
            SettingsPopup:
                id: settings_popup
        GameScreen:
            id: game_screen
            GameOverPopup:
                id: gameover_popup

并且gameoverpopup.kv:

<GameOverPopup>:
    auto_dismiss: False
    pos_hint: {'center_x': .5, 'center_y': .5}
    size_hint: .7, .4
    RelativeLayout:
        Button:
            id: close_button
            pos_hint: {'x': .1, 'y': .05}
            size_hint: .8, .2
            text: 'PLAY AGAIN'
            on_press: root.done()
        Label:
            pos_hint: {'x': .2, 'y': .8}
            size_hint: .6, .15
            font_size: 32
            text: 'YOU WON'

和main.py:

# kivy includes
Builder.load_file('startscreen.kv')
Builder.load_file('gamescreen.kv')
Builder.load_file('settingspopup.kv')
Builder.load_file('gameoverpopup.kv')

class StartScreen(Screen):
    pass

class GameScreen(Screen):
    pass

class ScreenMaster(ScreenManager):
    pass

class SettingsPopup(ModalView):
    pass

class GameOverPopup(ModalView):
    def done(self):
        self.dismiss()

class MainFrame(AnchorLayout):
    pass

class MainApp(App):
    def on_pause(self):
        return True

    def build(self):
        return MainFrame()

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

Play again按钮调用done()方法,但ModalView窗口小部件不会被忽略。我怎样才能解决这个问题并让它消失?

2 个答案:

答案 0 :(得分:0)

自己找到了解决方案:

<MainFrame>:
    id: main_frame
    ScreenMaster:
        id: screen_master
        StartScreen:
            id: start_screen
            SettingsPopup:
                id: settings_popup
                on_parent: if self.parent == start_screen: start_screen.remove_widget(self)
        GameScreen:
            id: game_screen
            GameOverPopup:
                id: gameover_popup
                on_parent: if self.parent == game_screen: game_screen.remove_widget(self)

因此我们实例化那些弹出窗口并立即关闭它们。现在我们可以随时打开它们。

答案 1 :(得分:0)

ModalView或从中继承的任何内容(Popup)并不意味着将其作为孩子添加到任何地方。默认情况下,ModalView会直接附加到Window,因为当您调用open()方法时,docs会提及open()

当您将其作为某个孩子添加到某个地方时,您会自动将其显示为 错误 ,因为您滥用了该窗口小部件的用途。

而不是你应该在某个地方将它作为一个类/规则,并在需要它时显示 调用 on_open方法。当您需要手动关闭它时,您需要将一些方法附加到ModalView以在某处存储dismiss()类的实例并通过该实例调用ModalView或放置ModalView上的某个按钮。

根据你的回答,你只能将你误操作小部件的错误告诉你。 :)

有两种方法可以打开Popup(或SettingsPopup().open() ):

<强>蟒:

#:import Factory kivy.factory.Factory
Factory.SettingsPopup().open()

<强> KV:

lst = [1,4,6,2,8,9,90]
the_index = lst.index(n)
lst2 = lst[the_index-1]