Search code examples
python-3.xkivy

How do I close a kivy application window with a button press?


I am making a snake game in Python using Pygame and I want to add a Menu screen using the Kivy Framework. I have a "play" button in the center, and when I click it I want to close the kivy window but not Python Program as I want the game to run after you click the button.

I have already tried using app.stop() but that only clears the kivy window and and the windows sits there covering the screen.


Solution

  • Bind on_request_close to a function that calls Window.close() (among other exit scripts).

    from kivy.app import App
    from kivy.core.window import Window
    from kivy.uix.gridlayout import GridLayout
    
    class GameApp(App):
           
        def build(self):
            return MenuScreen()
    
    class MenuScreen(GridLayout):
    
        def __init__(self, **kwargs):
            super(MenuScreen, self).__init__(**kwargs)   
            Window.bind(on_request_close=self.end_func)
    
        def end_func(self, *args):
            app.stop()
            Window.close()