We're back after a server migration that caused effbot.org to fall over a bit harder than expected. Expect some glitches.

Hello, Tkinter

But enough talk. Time to look at some code instead.

As you know, every serious tutorial should start with a “hello world”-type example. In this overview, we’ll show you not only one such example, but two.

First, let’s look at a pretty minimal version:

Our First Tkinter Program (File: hello1.py)
from Tkinter import *

root = Tk()

w = Label(root, text="Hello, world!")
w.pack()

root.mainloop()

Running the Example

To run the program, run the script as usual:

$ python hello1.py

The following window appears.

Running the program

To stop the program, just close the window.

Details

We start by importing the Tkinter module. It contains all classes, functions and other things needed to work with the Tk toolkit. In most cases, you can simply import everything from Tkinter into your module’s namespace:

from Tkinter import *

To initialize Tkinter, we have to create a Tk root widget. This is an ordinary window, with a title bar and other decoration provided by your window manager. You should only create one root widget for each program, and it must be created before any other widgets.

root = Tk()

Next, we create a Label widget as a child to the root window:

w = Label(root, text="Hello, world!")
w.pack()

A Label widget can display either text or an icon or other image. In this case, we use the text option to specify which text to display.

Next, we call the pack method on this widget. This tells it to size itself to fit the given text, and make itself visible. However, the window won’t appear until we’ve entered the Tkinter event loop:

root.mainloop()

The program will stay in the event loop until we close the window. The event loop doesn’t only handle events from the user (such as mouse clicks and key presses) or the windowing system (such as redraw events and window configuration messages), it also handle operations queued by Tkinter itself. Among these operations are geometry management (queued by the pack method) and display updates. This also means that the application window will not appear before you enter the main loop.