Previous Page
Next Page

17.2. Widget Fundamentals

Tkinter supplies many kinds of widgets, and most of them have several things in common. All widgets are instances of classes that inherit from class Widget. Class Widget itself is abstract; that is, you never instantiate Widget itself. You only instantiate concrete subclasses corresponding to specific kinds of widgets. Class Widget's functionality is common to all the widgets you instantiate.

To instantiate any kind of widget, call the widget's class. The first argument is the parent window of the widget, also known as the widget's master. If you omit this positional argument, the widget's master is the application's main window. All other arguments are in named form: option=value. To set or change options on an existing widget w, call w.config(option=value). To get an option of w call w.cget('option'), which returns the option's value. Each widget w is a mapping, so you can also get an option as w['option'], and set or change it with w['option']=value.

17.2.1. Common Widget Options

Many widgets accept some common options. Some options affect a widget's colors, while others affect lengths (normally in pixels), and there are various other kinds. This section details the most commonly used options. Color options

Tkinter represents colors with strings. The string can be a color name, such as 'red' or 'orange', or it may be of the form '#RRGGBB', where each R, G, and B are hexadecimal digits that represent a color by the values of red, green, and blue components on a scale of 0 to 255. Don't worry if your screen can't display millions of different colors, as implied by this scheme: Tkinter maps any requested color to the closest color that your screen can display. The common color options are:


Background color for the widget when the widget is active, meaning that the mouse is over the widget and clicking on it makes something happen


Foreground color for the widget when the widget is active

background (also bg)

Background color for the widget


Foreground color for the widget when the widget is disabled, meaning that clicking on the widget is ignored

foreground (also fg)

Foreground color for the widget


Background color of the highlight region when the widget has focus


Foreground color of the highlight region when the widget has focus


Background color for the selected items of the widget; for widgets that have selectable items, such as Listbox


Foreground color for the selected items of the widget Length options

Tkinter normally expresses a length as an integer number of pixels; other units of measure are possible, but rarely used. The common length options are:


Width of the border (if any), giving a three-dimensional look to the widget


Width of the highlight rectangle when the widget has focus (when 0, the widget does not draw a highlight rectangle)

padx pady

Extra space the widget requests from its layout manager beyond the minimum the widget needs to display its contents in the x and y directions


Width of the three-dimentional border (if any) around selected items of the widget


Maximum line length for widgets that perform word wrapping (when less than or equal to 0, there is no wrapping: the widget breaks lines of text only at '\n') Options expressing numbers of characters

Some options indicate a widget's requested layout not in pixels but rather as a number of characters, using average width or height of the widget's fonts:


Desired height of the widget; must be greater than or equal to 1


Index of the character to underline in the widget's text (0 is the first character, 1 the second one, and so on); the underlined character is the shortcut key to reach or activate the widget


Desired width of the widget (when less than or equal to 0, the desired width is just enough to hold the widget's current contents) Other common options

Other options accepted by many kinds of widgets are a mixed bag that deals with both behavior and looks:


Where the information in the widget is displayed; must be N, NE, E, SE, S, SW, W, NW, or CENTER (all except CENTER are compass directions).


Callable without arguments; executes when the user clicks on the widget (only for widgets Button, Checkbutton, and Radiobutton).


Font for the text in this widget (see "Fonts" on page 433).


An image to display in the widget instead of text; the value must be a Tkinter image object (see "Tkinter Images" on page 414).


How lines are justified when a widget shows more than a line of text; must be LEFT, CENTER, or RIGHT.


The three-dimensional effect that indicates how the interior of the widget appears relative to the exterior; must be RAISED, SUNKEN, FLAT, RIDGE, SOLID, or GROOVE.


Widget look and behavior on mouse and keyboard clicks; must be NORMAL, ACTIVE, or DISABLED.


If true, the widget accepts focus when the user navigates among widgets by pressing the Tab or Shift-Tab keys.


The text string displayed by the widget.


The Tkinter variable object associated with the widget (see "Tkinter Variable Objects" on page 413).

17.2.2. Common Widget Methods

A widget w supplies many methods. Besides event-related methods (covered in "Event-Related Methods" on page 448), commonly used widget methods are the following.



Returns the value configured in w for option.



w.config( ), called without arguments, returns a dictionary where each possible option of w is mapped to a tuple that describes the option's current setting. Called with one or more named arguments, config sets those options in w's configuration.


w.focus_set( )

Sets focus to w so that all keyboard events for the application are sent to w.

grab_set, grab_release

w.grab_set( ) w.grab_release( )

grab_set ensures that all of the application's events are sent to w until a corresponding call is made to grab_release.


w.mainloop( )

Enters a Tkinter event loop. Event loops may be nested; each call to mainloop enters one further nested level of the event loop.


w.quit( )

Quits a Tkinter event loop. When event loops are nested, each call to quit exits one nested level of the event loop.


w.update( )

Handles all pending events. Never call this while you're already handling an event!


w.update_idletasks( )

Handles those pending events that would normally be handled only when the event loop is idle (such as layout-manager updates and widget redrawing), but does not perform any callbacks. You can safely call this method at any time.



v must be a Tkinter variable object (covered in "Tkinter Variable Objects" on page 413). wait_variable returns only when the value of v changes. Meanwhile, other parts of the application remain active.



w1 must be a widget. wait_visibility returns only when w1 becomes visible. Meanwhile, other parts of the application remain active.



w1 must be a widget. wait_window returns only when w1 is destroyed. Meanwhile, other parts of the application remain active.


w.winfo_height( )

Returns w's height in pixels.


w.winfo_width( )

Returns w's width in pixels.

w supplies many other methods whose names start with winfo_, but the two above are the most often called, typically after calling w.update_idletasks. They let you ascertain a widget's dimensions after the user has resized a window, causing the layout manager to rearrange the widgets' layout.

17.2.3. Tkinter Variable Objects

The Tkinter module supplies classes whose instances represent variables. Each class deals with a specific data type: DoubleVar for float, IntVar for int, StringVar for str. Instantiate any of these classes without arguments to obtain an instance x, also known in Tkinter as a variable object, set to 0 or ''. x.set(datum) sets x's value to the given value; x.get( ) returns x's current value.

You can pass x as the textvariable or variable configuration option for a widget. Once you do this, the widget's text changes to track any change to x's value, and, for some kinds of widgets, x's value tracks changes to the widget. A Tkinter variable can control more than one widget. Tkinter variables let you control widgets more transparently, and sometimes more conveniently, than explicitly querying and setting widget properties. The following example shows how to use a StringVar to connect an Entry widget and a Label widget automatically:

import Tkinter

root = Tkinter.Tk( )
tv = Tkinter.StringVar( )
Tkinter.Label(textvariable=tv).pack( )
Tkinter.Entry(textvariable=tv).pack( )
Tkinter.Button(text="Exit", command=root.quit).pack( )

Tkinter.mainloop( )
print 'Final value is', tv.get( )

As you edit the Entry, you'll see the Label change automatically. This example instantiates the Tkinter main window explicitly, binds it to name root, and then sets as the Button's command the bound method root.quit, which quits Tkinter's main loop but does not terminate the Python application. Thus, the example ends with a print statement to show on standard output the final value of variable object tv.

17.2.4. Tkinter Images

The Tkinter class PhotoImage handles Graphical Interchange Format (GIF) and Portable PixMap (PPM) images. Call PhotoImage with a named argument file=path to load image data from the file at the given path and get an instance x.

You can set x as the image configuration option for one or more widgets. The widgets display the image rather than text. For image-processing functionality on many image formats (including JPEG, PNG, and TIFF), use PIL, the Python Imaging Library (, which is designed to work with Tkinter. I do not cover PIL further in this book.

Tkinter also supplies class BitmapImage, whose instances are usable wherever instances of PhotoImage are. BitmapImage supports some file formats known as "bitmaps." I do not cover BitmapImage further in this book.

Being set as the image configuration option of a widget is not enough to keep instances of PhotoImage and BitmapImage alive. Hold such instances in a Python container object, such as a list or dictionary, so that the instances are not garbage-collected. The following example shows how to display some GIF images:

import os import Tkinter

root = Tkinter.Tk( )
L = Tkinter.Listbox(selectmode=Tkinter.SINGLE)
gifsdict = {}

dirpath = 'imgs'
for gifname in os.listdir(dirpath):
    if not gifname[0].isdigit( ): continue
    gifpath = os.path.join(dirpath, gifname)
    gif = Tkinter.PhotoImage(file=gifpath)
    gifsdict[gifname] = gif
    L.insert(Tkinter.END, gifname)

L.pack( )
img = Tkinter.Label( )
img.pack( )
def list_entry_clicked(*ignore):
    imgname = L.get(L.curselection( )[0])
L.bind('<ButtonRelease-1>', list_entry_clicked)
root.mainloop( )

Assuming you have in some directory ('imgs' in the example) several GIF files whose filenames start with digits, the example loads the images into memory, shows the names in a Listbox instance, and shows in a Label instance the GIF whose file you click on. For simplicity, the example does not give the Listbox widget a Scrollbar (we'll see how to equip a Listbox with a Scrollbar in "Scrollbar" on page 419).

Previous Page
Next Page