Search code examples
pythonuser-interfacepygtk

Creating a sub-window with PyGTK


Im using PyGTK to create a gui in python and I cant figure out how to make make a sub-window. For example I have my main window:

class Main(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self, title="GCT")

        self.box = Gtk.Box()
        self.set_default_size(300, 300)
        self.set_position(Gtk.WindowPosition.CENTER)
        self.table = Gtk.Table(6, 5)

        self.button = Gtk.Button("sub-window")
        self.table.attach(self.button, 0, 2, 0, 1)

        self.box.add(self.table)
        self.add.(self.box)
        self.show_all()

When I click the sub-window button I would like to launch an new window independent from my main window and that will allow me to still operate the main window without closing the sub-window. How would I be able to do this?


Solution

  • from gi.repository import Gtk
    
    class AnotherWindow(Gtk.Window):
        def __init__(self):
            Gtk.Window.__init__(self, title="GCT")
            self.connect("destroy", lambda x: Gtk.main_quit())
    
            self.add(Gtk.Label("This is another window"))
            self.show_all()
    
    
    
    class Main(Gtk.Window):
        def __init__(self):
            Gtk.Window.__init__(self, title="GCT")
            self.connect("destroy", lambda x: Gtk.main_quit())
    
            self.box = Gtk.Box()
            self.set_default_size(300, 300)
            self.set_position(Gtk.WindowPosition.CENTER)
            self.table = Gtk.Table(6, 5)
    
            self.button = Gtk.Button("sub-window")
            self.button.connect("clicked", self.open_window)
            self.table.attach(self.button, 0, 2, 0, 1)
    
            self.box.add(self.table)
            self.add(self.box)
            self.show_all()
    
        def open_window(self, win):
            subw = AnotherWindow()
    
    
    def main():
        m = Main()
        Gtk.main()
        return 0
    
    if __name__ == '__main__':
        main()
    

    Each time you click on the sub_window button, another window will open. They will be piled on each other, so you won't see much :-)

    You should always add the connect to the destroy action - else the mainloop of Gtk will never stop, and you won't get control back to the keyboard.