How to create a child window in tkinter using classes?

Viewed 28

I am learning tkinter and decided to use classes to create child windows



class Window:
    def __init__(self, title, geometry, icon='default.ico'):
        self.root = Tk()
        self.title = self.root.title(title)
        self.geometry = self.root.geometry(geometry)
        self.icon = self.root.iconbitmap(icon)

    def run(self):
        self.root.mainloop()

    def child_window(self, title, geometry, icon='default.ico'):
        ChildWindow(self.root, title, geometry, icon)


class ChildWindow(Window):
    def __init__(self, parent, title, geometry, icon):
        self.child = Toplevel(parent)
        Window.__init__(self, title, geometry, icon)

    def run(self):
        self.child.mainloop()


x = Window('Window', '600x800')
x.child_window('Child window', '200x300')
x.run()

Everything works fine, but for some reason I have two child windows created at once

1 Answers

Creating an instance of Window creates a window. Since ChildWindow inherits from Window, it also creates a window. Then, insdide ChildWindow.__init__ you create a Toplevel, giving you a total of three windows.

Your ChildWindow probably shouldn't inherit from Window, since every instance of it or any subclasses will each create a new root window.

Related