Search code examples
pythonkivy

Can I Close Kivy Window and Open It Again?


Is there a way to launch kivy twice from the same process, while closing kivy's window when not needed? MWE:

from kivy.app import App
app = App ()
app.run ()
app.root_window.close ()
App().run () # ERROR: "no event listeners have been created" and "Application will leave"

I want the second App().run() to create another window, without having to re-launch Python. Is this possible?

What I'm trying to do is that I'm trying to debug a kivy program from the Python repl. I open the App, interact with it, find a bug, dismiss the window by clicking its "X" button, and then I go on to test (from the same repl) the non-GUI parts of the program that caused the bug. But the window sticks around all this time, which is a major nuisance as I use a tabbing window manager. I want to be able to close this window while I'm working on the non-GUI parts of the program, and then come back to launch the GUI again, without having to exit and restart the repl.


Solution

  • I found this on the web. Add a method:

    def reset():
        import kivy.core.window as window
        from kivy.base import EventLoop
        if not EventLoop.event_listeners:
            from kivy.cache import Cache
            window.Window = window.core_select_lib('window', window.window_impl, True)
            for cat in Cache._categories:
                Cache._objects[cat] = {}
    

    Then you can restart the app like this:

    from kivy.app import App
    app = App ()
    app.run ()
    app.root_window.close ()
    reset()
    App().run ()