O'Reilly logo

Programming Python, Second Edition by Mark Lutz

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Toplevel Windows

Tkinter GUIs always have a root window, whether you get it by default or create it explicitly by calling the Tk object constructor. This main root window is the one that opens when your program runs, and is where you generally pack your most important widgets. In addition, Tkinter scripts can create any number of independent windows, generated and popped up on demand, by creating Toplevel widget objects.

Each Toplevel object created produces a new window on the display, and automatically adds it to the program’s GUI event-loop processing stream (you don’t need to call the mainloop method of new windows to activate them). Example 7-3 builds a root and two pop-up windows.

Example 7-3. PP2E\Gui\Tour\toplevel0.py

import sys
from Tkinter import Toplevel, Button, Label

win1 = Toplevel()                  # two independent windows
win2 = Toplevel()                  # but part of same process

Button(win1, text='Spam', command=sys.exit).pack()
Button(win2, text='SPAM', command=sys.exit).pack()

Label(text='Popups').pack()        # on default Tk() root window
win1.mainloop()

The toplevel0 script gets a root window by default (that’s what the Label is attached to, since it doesn’t specify a real parent), but also creates two standalone Toplevel windows that appear and function independently of the root window, as seen in Figure 7-3.

Two Toplevel windows and a root window

Figure 7-3. Two Toplevel windows and a root window

The two Toplevel windows on ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required