[Tutor] Multiple windows in Tkinter

John Fouhy john at fouhy.net
Fri Oct 3 00:53:09 CEST 2008


2008/10/3 Glen Clark <glenuk at gmail.com>:
> What is toplevel? Is it the same as Tk()? Do I initialise a root using Tk()
> and then use toplevel for any other windows? How do I switch between the
> Windows? And while I am on the subject what is a frame and why should I use
> it? atm the moment it just seems to be the same as Tk()?

The answer to your third question is: Yes.  Toplevel() will create
another window that is managed by your window manager (this is
Explorer if you are using Microsoft Windows).  So you can switch to it
using alt-tab or command-` or whatever.  You can also programmatically
give it focus, although I forget how.

(to say that a widget has "focus" means "if you type on the keyboard,
this widget gets the keypresses")

Frames are containers. The main use for them is to put other widgets
into them for layout purposes.  For example, you might decide to split
your layout into two halves, with some kind of menu in the left, and
content in the right.  To do that, you would create two frames, pack
them left to right, then put the menu into the left frame and your
content into the right frame.

e.g. here is a short program that puts some buttons in the left and
uses them to change the colour of the right-hand frame.
(normally you would do something more complex :-) )

from Tkinter import *

tk = Tk()

# Left frame to hold buttons
left = Frame(tk)
left.pack(side=LEFT, expand=True, fill=Y)

# Right frame to hold display
right = Frame(tk, height=200, width=200)
right.pack(expand=True, fill=BOTH)

# change the colour of the right-hand frame
def changeColour(c):
    def change():
        right.config(background=c)
    return change

# Buttons
colours = ['red', 'green', 'blue', 'yellow']
for c in colours:
    b = Button(left, text=c, command=changeColour(c))
    b.pack(side=TOP, expand=True)

tk.mainloop()

-- 
John.


More information about the Tutor mailing list