[Tutor] Pattern for using multiple windows in Tkinter

Alan Gauld alan.gauld at btinternet.com
Mon May 3 19:28:27 CEST 2010


"The Green Tea Leaf" <thegreentealeaf at gmail.com> wrote

> I've just started to play with Tkinter and can't really figure out the
> typical pattern of creating an app with several windows - I tried to
> find some resources on the web but failed to find how to do this. Here
> is an attempt to explain using code
> 
> class MyWindowClass:
>  def __init__(self):
>    self._window = Toplevel() # Is this the correct pattern for

Rather than having an instance of TopLevel inside and delegating 
everything I'd probably go for inheriting from TopLevel, because 
in this case you really do want your class to be a kind of TopLevel, 
rather than just having a Toplevel.

And then you need to add a parent parameter to init() and when 
you instantiate it pass the top Tk() as the parent.

> first = MyWindowClass()
> second = MyWindowClass()
> 
> This works but it also creates the "root" window ...

I think you always need a root window, the trick is 
to hide it  - maybe by making it very small and/or  
unmapping it from the screen.

> What is the "correct" way of coding an app where I define a class that
> represents one window and where I want to be able to open multiple
> windows of that class.

A subclass of toplevel should do that but I confess I haven't 
actually done it. I might have a go later just for fun!

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list