Search code examples
pythonpython-3.xuser-interfacegtk3pygobject

Proper way to open multiple appwindows with Python GTK3 Gtk.Application


I'm learning GTK3 under Python3 and made an app that has only one AppWindow so far. I'm using Gtk.Application.

I can't figure out how to proper handle opening a second window. I can open it directly from my main Window but I don't know how to pass Application object to it (I googled and "duckduckgoed" without any success).

  • Do I need to call Gtk.Application to open second window?
  • How do I let Gtk.Application track this new window?

Application is like this:

  • Main window with an objects list from a database.
  • Second window to edit a single item selected from the main window's list.

Thanks.

My code (I stripped out the unnecesary code):

# ################################################################
# MAIN APP WINDOW
class AppWindow(Gtk.ApplicationWindow):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # Here all the widgets and a button to open the second window

        self.show_all()

# ################################################################
# MAIN APP CLASS
class Application(Gtk.Application):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, application_id=MIKUNA_ID,
                         **kwargs)
        self.window = None

    def do_startup(self):
        Gtk.Application.do_startup(self)

        action = Gio.SimpleAction.new("quit", None)
        action.connect("activate", self.on_quit)
        self.add_action(action)

    def do_activate(self):
        # We only allow a single window and raise any existing ones
        if not self.window:
            # Windows are associated with the application
            # when the last one is closed the application shuts down
            self.window = AppWindow(application=self, title="Mikuna")

        self.window.present()

    def on_quit(self, action, param):
        self.quit()

if __name__ == "__main__":
    app = Application()
    app.run(sys.argv)

Solution

  • Second window to edit a single item selected from the main window's list.

    You just create the second window from your main window then, probably a Gtk.Dialog that is transient to the main window. You only need to make the Application track it if it is a toplevel window you expect to out-live your main window.