Tkinter Reference A GUI For Python
Tkinter Reference A GUI For Python
Tkinter Reference A GUI For Python
for Python
John W. Shipman
2004-06-03 16:13
Table of Contents
1. What is Tkinter? ...................................................................................................................... 2
2. A minimal application .............................................................................................................. 3
3. Layout management ................................................................................................................ 3
3.1. The .grid() method .................................................................................................... 4
3.2. Other grid management methods ................................................................................... 5
4. Standard attributes .................................................................................................................. 5
4.1. Dimensions ................................................................................................................... 5
4.2. Coordinate system ......................................................................................................... 6
4.3. Colors ........................................................................................................................... 6
4.4. Type fonts ..................................................................................................................... 6
4.5. Anchors ........................................................................................................................ 8
4.6. Relief styles ................................................................................................................... 8
4.7. Bitmaps ........................................................................................................................ 8
4.8. Cursors ......................................................................................................................... 9
4.9. Images ........................................................................................................................ 11
4.10. Geometry strings ....................................................................................................... 11
4.11. Window names .......................................................................................................... 12
5. The Button widget ................................................................................................................ 12
6. The Canvas widget ................................................................................................................ 14
6.1. Canvas concepts .......................................................................................................... 15
6.2. Methods on Canvas objects ......................................................................................... 16
6.3. The canvas arc object ................................................................................................... 20
6.4. The canvas bitmap object ............................................................................................. 20
6.5. The canvas image object ............................................................................................... 21
6.6. The canvas line object .................................................................................................. 21
6.7. The canvas oval object .................................................................................................. 22
6.8. The canvas polygon object ............................................................................................ 23
6.9. The canvas rectangle object .......................................................................................... 24
6.10. The canvas text object ................................................................................................. 24
6.11. The canvas window object .......................................................................................... 25
7. The Checkbutton widget ...................................................................................................... 25
8. The Entry widget .................................................................................................................. 28
8.1. Scrolling an Entry widget ........................................................................................... 31
9. The Frame widget .................................................................................................................. 32
10. The Label widget ................................................................................................................ 33
11. The Listbox widget ............................................................................................................ 34
11.1. Scrolling a Listbox widget ....................................................................................... 37
12. The Menu widget .................................................................................................................. 37
1.What is Tkinter?
Tkinter is a GUI (graphical user interface) widget set for Python. This document contains only the
commoner features.
This document applies to Python 1.5 and Tkinter 8.0.4 running in the X Window system under Linux.
Your version may vary.
Pertinent references:
An Introduction to Tkinter [http://www.pythonware.com/library/tkinter/introduction/index.htm]
by Fredrik Lundh
Python and Tkinter Programming by John Grayson (Manning, 2000, ISBN 1-884777-81-3).
Python 2.2 quick reference [http://www.nmt.edu/tcc/help/pubs/python22/]: general information
about the Python language.
This publication is available in Web form [http://www.nmt.edu/tcc/help/pubs/tkinter/] and also
as a PDF document (82 pp.) [http://www.nmt.edu/tcc/help/pubs/tkinter/tkinter.pdf].
class Application(Frame): 3
def __init__(self, master=None):
Frame.__init__(self, master) 4
self.grid() 5
self.createWidgets()
def createWidgets(self):
self.quitButton = Button ( self, text="Quit",
command=self.quit ) 6
self.quitButton.grid() 7
app = Application() 8
app.master.title("Sample application") 9
app.mainloop() 10
1 This line makes the script self-executing, assuming that your system has the Python interpreter at
path /usr/local/bin/python.
2 This line imports the entire Tkinter package into your program's namespace.
3 Your application class must inherit from Tkinter's Frame class.
4 Calls the constructor for the parent class, Frame.
5 Necessary to make the application actually appear on the screen.
6 Creates a button labeled Quit.
7 Places the button on the application.
8 The main program starts here by instantiating the Application class.
9 This method call sets the title of the window to Sample application.
10 Starts the application's main loop, waiting for mouse and keyboard events.
3.Layout management
Later we will discuss the widgets, the building blocks of your GUI application. How do widgets get
arranged in a window?
Although there are three different geometry managers in Tkinter, the author strongly prefers the
.grid() geometry manager for pretty much everything. This manager treats every window or frame
as a tablea gridwork of rows and columns.
A cell is the area at the intersection of one row and one column.
The width of each column is the width of the widest cell in that column.
The height of each row is the height of the largest cell in that row.
column The column number where you want the widget gridded, counting from
zero. The default value is zero.
columnspan Normally a widget occupies only one cell in the grid. However, you can grab
multiple cells of a row and merge them into one larger cell by setting the
columnspan option to the number of cells. For example, w.grid(row=0,
column=2, columnspan=3) would place widget w in a cell that spans
columns 2, 3, and 4 of row 0.
ipadx Internal x padding. This dimension is added inside the widget inside its left
and right sides.
ipady Internal y padding. This dimension is added inside the widget inside its top
and bottom borders.
padx External x padding. This dimension is added to the left and right outside the
widget.
pady External y padding. This dimension is added above and below the widget.
row The row number into which you want to insert the widget, counting from 0.
The default is the next higher-numbered unoccupied row.
rowspan Normally a widget occupies only one cell in the grid. You can grab multiple
adjacent cells of a column, however, by setting the rowspan option to the
number of cells to grab. This option can be used in combination with the
columnspan option to grab a block of cells. For example, w.grid(row=3,
column=2, rowspan=4, columnspan=5) would place widget w in an
area formed by merging 20 cells, with row numbers 36 and column numbers
26.
sticky This option determines how to distribute any extra space within the cell that
is not taken up by the widget at its natural size. See below.
If you do not provide a sticky attribute, the default behavior is to center the widget in the cell.
w.grid_forget()
This method makes widget w disappear from the screen. It still exists, it just isn't visible. You can
use .grid() it to make it appear again, but it won't remember its grid options.
w.grid_propagate()
Normally, all widgets propagate their dimensions, meaning that they adjust to fit the contents.
However, sometimes you want to force a widget to be a certain size, regardless of the size of its
contents. To do this, call w.grid_propagate(0) where w is the widget whose size you want to
force.
w.grid_remove()
This method is like .grid_forget(), but its grid options are remembered, so if you .grid() it
again, it will use the same grid configuration options.
4.Standard attributes
Before we look at the widgets, let's take a look at how some of their common attributessuch as sizes,
colors and fontsare specified.
Each widget has a set of options that affect its appearance and behaviorattributes such as fonts,
colors, sizes, text labels, and such.
You can specify options when calling the widget's constructor using keyword arguments such as
text="PANIC!" or height=20.
After you have created a widget, you can later change any option by using the widget's .config()
method, and retrieve the current setting of any option by using the widget's .cget() method. See
Section19, Universal widget methods (p. 62) for more on these methods.
4.1.Dimensions
Various lengths, widths, and other dimensions of widgets can be described in many different units.
If you set a dimension to an integer, it is assumed to be in pixels.
You can specify units by setting a dimension to a string containing a number followed by:
c Centimeters
i Inches
4.2.Coordinate system
As in most contemporary display systems, the origin of each coordinate system is at its upper left corner,
with the x coordinate increasing toward the right, and the y coordinate increasing toward the bottom:
+x
+y
The base unit is the pixel, with the top left pixel having coordinates (0,0). Coordinates that you specify
as integers are always expressed in pixels, but any coordinate may be specified as a dimensioned
quantity; see Section4.1, Dimensions (p. 5).
4.3.Colors
There are two general ways to specify colors in Tkinter.
You can use a string specifying the proportion of red, green, and blue in hexadecimal digits:
For example, "#fff" is white, "#000000" is black, "#000fff000" is pure green, and "#00ffff"
is pure cyan (green plus blue).
You can also use any locally defined standard color name. The colors "white", "black", "red",
"green", "blue", "cyan", "yellow", and "magenta" will always be available. Other names
may work, depending on your local installation.
4.4.Type fonts
Depending on your platform, there may be up to three ways to specify type style.
As a tuple whose first element is the font family, followed by a size in points, optionally followed
by a string containing one or more of the style modifiers bold, italic, underline, and over-
strike.
Examples: ("Helvetica", "16") for a 16-point Helvetica regular; ("Times", "24", "bold
italic") for a 24-point Times bold italic.
You can create a font object by importing the tkFont module and using its Font class constructor:
import tkFont
.actual ( option=None )
If you pass no arguments, you get back a dictionary of the font's actual attributes, which may differ
from the ones you requested. To get back the value of an attribute, pass its name as an argument.
.cget ( option )
Returns the value of the given option.
.configure ( option, ... )
Use this method to change one or more options on a font. For example, if you have a Font object
called titleFont, if you call titleFont.configure ( family="times", size=18 ), that
font will change to 18pt Times and any widgets that use that font will change too.
.copy()
Returns a copy of a Font object.
.measure ( text )
Pass this method a string, and it will return the number of pixels of width that string will take in
the font. Warning: some slanted characters may extend outside this area.
.metrics ( option )
If you call this method with no arguments, it returns a dictionary of all the font metrics. You can re-
trieve the value of just one metric by passing its name as an argument. Metrics include:
ascent Number of pixels of height between the baseline and the top of the highest as-
cender.
descent Number of pixels of height between the baseline and the bottom of the lowest
ascender.
fixed This value is 0 for a variable-width font and 1 for a monospaced font.
linespace Number of pixels of height total. This is the leading of type set solid in the
given font.
NW N NE
W CENTER E
SW S SE
For example, if you create a small widget inside a large frame and use the anchor=SE option, the
widget will be placed in the bottom right corner of the frame. If you used anchor=N instead, the widget
would be centered along the top edge.
Anchors are also used to define where text is positioned relative to a reference point. For example, if
you use CENTER as a text anchor, the text will be centered horizontally and vertically around the reference
point. Anchor NW will position the text so that the reference point coincides with the northwest (top left)
corner of the box containing the text. Anchor W will center the text vertically around the reference point,
with the left edge of the text box passing through that point, and so on.
4.6.Relief styles
The relief style of a widget refers to certain simulated 3-D effects around the outside of the widget. Here
is a screen shot of a row of buttons exhibiting all the possible relief styles:
The width of these borders depends on the borderwidth attribute of the widget. The above graphic
shows what they look like with a 5-pixel border; the default border width is 2.
4.7.Bitmaps
For bitmap options in widgets, these bitmaps are guaranteed to be available:
The graphic above shows Button widgets bearing the standard bitmaps. From left to right, they are
"error", "gray75", "gray50", "gray25", "gray12", "hourglass", "info", "questhead",
"question", and "warning".
You can use your own bitmaps. Any file in .xbm (X bit map) format will work. In place of a standard
bitmap name, use the string "@" followed by the pathname of the .xbm file.
4.9.Images
To use graphic images in a Tkinter application, Tkinter must be configured to include the Python Imaging
Library (PIL).
Refer to the author's companion document for PIL documentation: Python Imaging Library (PIL) quick
reference [http://www.nmt.edu/tcc/help/pubs/pil/]. Objects of the ImageTk class can be used in
Tkinter applications.
4.10.Geometry strings
A geometry string is a standard way of describing the size and location of a top-level window on a
desktop.
A geometry string has this general form:
"wxhxy"
where:
The w and h parts give the window width and height in pixels. They are separated by the character
"x".
If the next part has the form +x, it specifies that the left side of the window should be x pixels from
the left side of the desktop. If it has the form -x, the right side of the window is x pixels from the
right side of the desktop.
If the next part has the form +y, it specifies that the top of the window should be y pixels below the
top of the desktop. If it has the form -y, the bottom of the window will be y pixels above the bottom
edge of the desktop.
For example, a window created with geometry="120x50-0+20" would be 120 pixels wide by 50
pixels high, and its top right corner will be along the right edge of the desktop and 20 pixels below the
top edge.
The path name for any widget w can be determined by calling str(w).
See also Section19, Universal widget methods (p. 62) for methods you can use to operate on window
names, especially the .winfo_name, .winfo_parent, and .winfo_pathname methods.
.flash()
Causes the button to flash several times between active and normal colors. Leaves the button in the
state it was in originally. Ignored if the button is disabled.
.invoke()
Calls the button's callback, and returns what that function returns. Has no effect if the button is
disabled or there is no callback.
6.1.Canvas concepts
Before we discuss the methods on canvases, we need to define some terms:
6.1.3.Object ID
The object ID of an object on the canvas is the value returned by the constructor for that object. All object
ID values are simple integers, and the object ID of an object is unique within that canvas.
6.1.4.Canvas tags
A tag is a string that you can associate with objects on the canvas.
A tag can be associated with any number of objects on the canvas, including zero.
An object can have any number of tags associated with it, including zero.
colormode Use "color" for color output, "gray" for grayscale, or "mono" for black and
white.
file If supplied, names a file where the PostScript will be written. If this option is
not given, the PostScript is returned as a string.
height How much of the Y size of the canvas to print. Default is all.
rotate If false, the page will be rendered in portrait orientation; if true, in landscape.
x Leftmost canvas coordinate of the area to print.
y Topmost canvas coordinate of the area to print.
width How much of the X size of the canvas to print. Default is all.
extent Width of the slice in degrees. The slice starts at the angle given by the start option
and extends counterclockwise for extent degrees.
fill By default, the interior of an arc is transparent, and fill="" will select this beha-
vior. You can also set this option to any color and the interior of the arc will be
filled with that color.
outline The color of the border around the outside of the slice. Default is black.
outlinestipple If the outline option is used, this option specifies a bitmap used to stipple the
border. Default is black, and that default can be specified by setting outlines-
tipple="".
start Starting angle for the slice, in degrees, measured from +x direction. If omitted,
you get the entire ellipse.
stipple A bitmap indicating how the interior fill of the arc will be stippled. Default is
stipple="" (solid). You'll probably want something like stipple="gray25".
Has no effect unless fill has been set to some color.
style The default is to draw the whole arc; use style=PIESLICE for this style. To draw
only the circular arc at the edge of the slice, use style=ARC. To draw the circular
arc and the chord (a straight line connecting the endpoints of the arc), use
style=CHORD.
width Width of the border around the outside of the arc. Default is 1 pixel.
anchor The bitmap is positioned relative to point (x, y). The default is anchor=CEN-
TER, meaning that the bitmap is centered on the (x, y) position. See Sec-
tion4.5, Anchors (p. 8) for the various anchor option values. For ex-
ample, if you specify anchor=NE, the bitmap will be positioned so that
point (x, y) is located at the northeast (top right) corner of the bitmap.
background The color that will appear where there are 0 values in the bitmap. The
default is background="", meaning transparent.
bitmap The bitmap to be displayed; see Section4.7, Bitmaps (p. 8).
foreground The color that will appear where there are 1 values in the bitmap. The
default is foreground="black".
tags The tags to be associated with the object, as a sequence of strings.
anchor The default is anchor=CENTER, meaning that the image is centered on the (x, y)
position. See Section4.5, Anchors (p. 8) for the possible values of this option.
For example, if you specify anchor=S, the image will be positioned so that point
(x, y) is located at the center of the bottom (south) edge of the image.
image The image to be displayed. See Section4.9, Images (p. 11), above, for information
about how to create images that can be loaded onto canvases.
tags The tags to be associated with the object, as a sequence of strings. See Section6.1.4,
Canvas tags (p. 15).
arrow The default is for the line to have no arrowheads. Use arrow=FIRST to get an
arrowhead at the (x0, y0) end of the line. Use arrow=LAST to get an arrowhead
at the far end. Use arrow=BOTH for arrowheads at both ends.
d2
d3
d1
(x0, y0)
(x1,y1)
The oval will coincide with the top and left-hand lines of this box, but will fit just inside the bottom and
right-hand sides.
To create an ellipse on a canvas C, use:
id = C.create_oval ( x0, y0, x1, y1, option, ... )
which returns the object ID of the new oval object on canvas C.
Options for ovals:
fill The default appearance of ellipse is transparent, and a value of fill="" will select
this behavior. You can also set this option to any color and the interior of the ellipse
will be filled with that color; see Section4.3, Colors (p. 6).
(x0,y0)
(x1,y1)
(x4,y4) (x3,y3)
fill You can color the interior by setting this option to a color. The default appearance
for the interior of a polygon is transparent, and you can set fill="" to get this
behavior. See Section4.3, Colors (p. 6).
outline Color of the outline; defaults to outline="black". Use outline="" to make
the outline transparent.
smooth The default outline uses straight lines to connect the vertices; use smooth=0 to
get that behavior. If you use smooth=1, you get a continuous spline curve.
Moreover, if you set smooth=1, you can make any segment straight by duplicating
the coordinates at each end of that segment.
splinesteps If the smooth option is true, each spline is rendered as a number of straight line
segments. The splinesteps option specifies the number of segments used to
approximate each section of the line; the default is splinesteps=12.
stipple A bitmap indicating how the interior of the polygon will be stippled. Default is
stipple="", which means a solid color. A typical value would be
stipple="gray25". Has no effect unless the fill has been set to some color.
See Section4.7, Bitmaps (p. 8).
fill By default, the interior of a rectangle is empty, and you can get this behavior with
fill="". You can also set the option to a color; see Section4.3, Colors (p. 6).
outline The color of the border. Default is outline="black".
stipple A bitmap indicating how the interior of the rectangle will be stippled. Default is
stipple="", which means a solid color. A typical value would be
stipple="gray25". Has no effect unless the fill has been set to some color.
See Section4.7, Bitmaps (p. 8).
tags The tags to be associated with the object, as a sequence of strings. See Section6.1.4,
Canvas tags (p. 15).
width Width of the border. Default is 1 pixel. Use width=0 to make the border invisible.
See Section4.1, Dimensions (p. 5).
anchor The default is anchor=CENTER, meaning that the text is centered vertically and
horizontally around position (x, y). See Section4.5, Anchors (p. 8) for possible
values. For example, if you specify anchor=SW, the text will be positioned so its
lower left corner is at point (x, y).
fill The default text color is black, but you can render it in any color by setting the
fill option to that color. See Section4.3, Colors (p. 6).
font If you don't like the default font, set this option to any font value. See Section4.4,
Type fonts (p. 6).
justify For multi-line textual displays, this option controls how the lines are justified:
LEFT (the default), CENTER, or RIGHT.
anchor The default is anchor=CENTER, meaning that the window is centered on the (x,
y) position. See Section4.5, Anchors (p. 8) for the possible values. For example,
if you specify anchor=E, the window will be positioned so that point (x, y) is on
the midpoint of its right-hand (east) edge.
height The height of the area reserved for the window. If omitted, the window will be
sized to fit the height of the contained widget. See Section4.1, Dimensions (p. 5)
for possible values.
tags The tags to be associated with the object, as a sequence of strings. See Section6.1.4,
Canvas tags (p. 15).
width The width of the area reserved for the window. If omitted, the window will be
sized to fit the width of the contained widget.
window Use window=w where w is the widget you want to place onto the canvas. If this is
omitted initially, you can later call C.itemconfigure ( id, window=w) to
place the widget w onto the canvas, where id is the window's object ID..
The purpose of a checkbutton widget (sometimes called checkbox) is to allow the user to read and
select a two-way choice. The graphic above shows how checkbuttons look in the off (0) and on (1) state
in one implementation: this is a screen shot of two checkbuttons using 24-point Times font.
activebackground Background color when the checkbutton is under the cursor. See Sec-
tion4.3, Colors (p. 6).
activeforeground Foreground color when the checkbutton is under the cursor.
anchor If the widget inhabits a space larger than it needs, this option specifies
where the checkbutton will sit in that space. The default is anchor=CEN-
TER. See Section4.5, Anchors (p. 8) for the allowable values. For ex-
ample, if you use anchor=NW, the widget will be placed in the upper left
corner of the space.
bg or background The normal background color displayed behind the label and indicator.
See Section4.3, Colors (p. 6).
bitmap To display a monochrome image on a button, set this option to a bitmap;
see Section4.7, Bitmaps (p. 8).
bd or borderwidth The size of the border around the indicator. Default is 2 pixels. For possible
values, see Section4.1, Dimensions (p. 5).
command A procedure to be called every time the user changes the state of this
checkbutton.
cursor If you set this option to a cursor name (see Section4.8, Cursors (p. 9)),
the mouse cursor will change to that pattern when it is over the checkbut-
ton.
disabledforeground The foreground color used to render the text of a disabled checkbutton.
The default is a stippled version of the default foreground color.
font The font used for the text. See Section4.4, Type fonts (p. 6).
fg or foreground The color used to render the text.
height The number of lines of text on the checkbutton. Default is 1.
highlightbackground The color of the focus highlight when the checkbutton does not have focus.
See Section23, Focus: routing keyboard input (p. 74).
highlightcolor The color of the focus highlight when the checkbutton has the focus.
highlightthickness The thickness of the focus highlight. Default is 1. Set to 0 to suppress
display of the focus highlight.
.deselect()
Clears (turns off) the checkbutton.
.flash()
Flashes the checkbutton a few times between its active and normal colors, but leaves it the way it
started.
.invoke()
You can call this method to get the same actions that would occur if the user clicked on the check-
button to change its state.
.select()
Sets (turns on) the checkbutton.
.toggle()
Clears the checkbutton if set, sets it if cleared.
bg or background The background color inside the entry area. Default is a light gray.
bd or borderwidth The width of the border around the entry area. Default is 2.
cursor The cursor used when the mouse is within the entry widget; see Sec-
tion4.8, Cursors (p. 9).
font The font used for text entered in the widget by the user. See Section4.4,
Type fonts (p. 6).
exportselection By default, if you select text within an Entry widget, it is automatically
exported to the clipboard. To avoid this exportation, use exportselec-
tion=0.
fg or foreground The color used to render the text. Default is black.
highlightbackground Color of the focus highlight when the widget does not have focus. See
Section23, Focus: routing keyboard input (p. 74).
highlightcolor Color shown in the focus highlight when the widget has the focus.
highlightthickness Thickness of the focus highlight.
insertbackground By default, the insertion cursor (which shows the point within the text
where new keyboard input will be inserted) is black. To get a different
color of insertion cursor, set insertbackground to any color; see Sec-
tion4.3, Colors (p. 6).
insertborderwidth By default, the insertion cursor is a simple rectangle. You can get the
cursor with the RAISED relief effect (see Section4.6, Relief styles (p. 8))
by setting insertborderwidth to the dimension of the 3-d border. If
you do, make sure that the insertwidth attribute is at least twice that
value.
insertofftime By default, the insertion cursor blinks. You can set insertofftime to
a value in milliseconds to specify how much time the insertion cursor
spends off. Default is 300. If you use insertofftime=0, the insertion
cursor won't blink at all.
insertontime Similar to insertofftime, this attribute specifies how much time the
cursor spends on per blink. Default is 600 (milliseconds).
insertwidth By default, the insertion cursor is 2 pixels wide. You can adjust this by
setting insertwidth to any dimension.
justify This option controls how the text is justified when the text doesn't fill the
widget's width. The value can be LEFT (the default), CENTER, or RIGHT.
relief Selects three-dimensional shading effects around the text entry. See Sec-
tion4.6, Relief styles (p. 8). The default is relief=SUNKEN
if op == "scroll":
bg or background The frame's background color. See Section4.3, Colors (p. 6).
bd or borderwidth Width of the frame's border. The default is 0 (no border). For permitted
values, see Section4.1, Dimensions (p. 5).
cursor The cursor used when the mouse is within the frame widget; see Sec-
tion4.8, Cursors (p. 9).
height The vertical dimension of the new frame. This will be ignored unless you
also call .grid_propagate(0) on the frame.
highlightbackground Color of the focus highlight when the frame does not have focus. See
Section23, Focus: routing keyboard input (p. 74).
highlightcolor Color shown in the focus highlight when the frame has the focus.
highlightthickness Thickness of the focus highlight.
relief The default relief for a frame is FLAT, which means the frame will blend
in with its surroundings. To put a border around a frame, set its border-
width to a positive value and set its relief to one of the standard relief
types; see Section4.6, Relief styles (p. 8).
takefocus Normally, frame widgets are not visited by input focus (see Section23,
Focus: routing keyboard input (p. 74) for an overview of this topic).
However, you can set takefocus=1 if you want the frame to receive
keyboard input. To handle such input, you will need to create bindings
for keyboard events; see Section24, Events (p. 75) for more on events
and bindings.
width The horizontal dimension of the new frame. See Section4.1, Dimen-
sions (p. 5). This value be ignored unless you also call
.grid_propagate(0) on the frame.
anchor This options controls where the text is positioned if the widget has more
space than the text needs. The default is anchor=CENTER, which centers
the text in the available space. For other values, see Section4.5, An-
chors (p. 8). For example, if you use anchor=NW, the text would be
positioned in the upper left-hand corner of the available space.
bg or background The background color of the label area. See Section4.3, Colors (p. 6).
bitmap Set this option equal to a bitmap or image object and the label will display
that graphic. See Section4.7, Bitmaps (p. 8) and Section4.9, Im-
ages (p. 11).
bd or borderwidth Width of the border around the label. Default is 2.
cursor Cursor that appears when the mouse is over this label. See Section4.8,
Cursors (p. 9).
font If you are displaying text in this label (with the text or textvariable
option, the font option specifies in what font that text will be displayed.
See Section4.4, Type fonts (p. 6).
fg or foreground If you are displaying text or a bitmap in this label, this option specifies
the color of the text. If you are displaying a bitmap, this is the color that
will appear at the position of the 1-bits in the bitmap. See Section4.3,
Colors (p. 6).
height Height of the label in lines (not pixels!). If this option is not set, the label
will be sized to fit its contents.
image To display a static image in the label widget, set this option to an image
object. See Section4.9, Images (p. 11).
justify Specifies how multiple lines of text will be aligned with respect to each
other: LEFT for flush left, CENTER for centered (the default), or RIGHT
for right-justified.
padx Extra space added to the left and right of the text within the widget. De-
fault is 1.
pady Extra space added above and below the text within the widget. Default
is 1.
relief Specifies the appearance of a decorative border around the label. The
default is FLAT; for other values, see Section4.6, Relief styles (p. 8).
takefocus Normally, focus does not cycle through Label widgets; see Section23,
Focus: routing keyboard input (p. 74). If you want this widget to be
visited by the focus, set takefocus=1.
text To display one or more lines of text in a label widget, set this option to a
string containing the text. Internal newlines ("\n") will force a line break.
There are no special methods for label widgets other than the common ones (see Section19, Universal
widget methods (p. 62)).
takefocus Normally, the focus will tab through listbox widgets. Set this option to 0
to take the widget out of the sequence. See Section23, Focus: routing
keyboard input (p. 74).
width The width of the widget in characters (not pixels!). The width is based on
an average character, so some strings of this length in proportional fonts
may not fit. The default is 20.
xscrollcommand If you want to allow the user to scroll the listbox horizontally, you can
link your listbox widget to a horizontal scrollbar. Set this option to the
.set method of the scrollbar. See Section11.1, Scrolling a Listbox
widget (p. 37) for more on scrollable listbox widgets.
yscrollcommand If you want to allow the user to scroll the listbox vertically, you can link
your listbox widget to a vertical scrollbar. Set this option to the .set
method of the scrollbar. See Section11.1, Scrolling a Listbox wid-
get (p. 37).
A special set of index forms is used for many of the methods on listbox objects:
If you specify an index as an integer, it refers to the line in the listbox with that index, counting from
0.
Index END refers to the last line in the listbox.
Index ACTIVE refers to the selected line. If the listbox allows multiple selections, it refers to the line
that was last selected.
An index string of the form "@x,y" refers to the line closest to coordinate (x,y) relative to the widget's
upper left corner.
Methods on listbox objects include:
.activate ( index )
Selects the line specifies by the given index.
.curselection()
Returns a tuple containing the line numbers of the selected element or elements, counting from 0.
If nothing is selected, returns an empty tuple.
Refer to Section13, The Menubutton widget (p. 40), below, to see how to create a menubutton and
connect it to a menu widget. First let's look at the Menu widget, which displays the list of choices.
The choices displayed on a menu may be any of these things:
A simple command: a text string (or image) that the user can select to perform some operation.
A cascade: a text string or image that the user can select to show another whole menu of choices.
A checkbutton (see Section7, The Checkbutton widget (p. 25)).
A group of radiobuttons (see Section14, The Radiobutton widget (p. 42)).
To create a menu widget, you must first have created a Menubutton, which we will call mb:
w = Menu ( mb, option, ... )
This constructor returns a new menu widget. Options include:
These methods are available on Menu objects. The ones that create choices on the menu have their own
particular options; see Section12.1, Menu item creation (coption) options (p. 39).
activebackground The background color when the mouse is over the menubutton. See Sec-
tion4.3, Colors (p. 6).
activeforeground The foreground color when the mouse is over the menubutton.
anchor This options controls where the text is positioned if the widget has more
space than the text needs. The default is anchor=CENTER, which centers
the text. For other options, see Section4.5, Anchors (p. 8). For example,
if you use anchor=W, the text would be centered against the left side of
the widget.
bg or background The background color when the mouse is not over the menubutton.
bitmap To display a bitmap on the menubutton, set this option to a bitmap name;
see Section4.7, Bitmaps (p. 8).
bd or borderwidth Width of the border around the menubutton. Default is 2 pixels. For
possible values, see Section4.1, Dimensions (p. 5).
cursor The cursor that appears when the mouse is over this menubutton. See
Section4.8, Cursors (p. 9).
direction Normally, the menu will appear below the menubutton. Set direc-
tion=LEFT to display the menu to the left of the button; use direc-
tion=RIGHT to display the menu to the right of the button; or use dir-
ection=ABOVE to place the menu above the button.
disabledforeground The foreground color shown on this menubutton when it is disabled.
fg or foreground The foreground color when the mouse is not over the menubutton.
height The height of the menubutton in lines of text (not pixels!). The default is
to fit the menubutton's size to its contents.
highlightbackground Color of the focus highlight when the widget does not have focus. See
Section23, Focus: routing keyboard input (p. 74).
highlightcolor Color shown in the focus highlight when the widget has the focus.
highlightthickness Thickness of the focus highlight.
image To display an image on this menubutton, set this option to the image
object. See Section4.9, Images (p. 11).
justify This option controls where the text is located when the text doesn't fill
the menubutton: use justify=LEFT to left-justify the text (this is the
default); use justify=CENTER to center it, or justify=RIGHT to right-
justify.
menu To associate the menubutton with a set of choices, set this option to the
Menu object containing those choices. That menu object must have been
created by passing the associated menubutton to the constructor as its
first argument. See below for an example showing how to associate a
menubutton and menu.
padx How much space to leave to the left and right of the text of the
menubutton. Default is 1.
pady How much space to leave above and below the text of the menubutton.
Default is 1.
Here is a brief example showing the creation of a menubutton and its associated menu with three
checkboxes:
self.mb = Menubutton ( self, text="condiments",
relief=RAISED )
self.mb.grid()
self.mayoVar = IntVar()
self.ketchVar = IntVar()
self.mb.menu.add_checkbutton ( label="mayo",
variable=self.mayoVar )
self.mb.menu.add_checkbutton ( label="ketchup",
variable=self.ketchVar )
This example creates a menubutton labeled condiments. When clicked, two checkbuttons labeled
mayo and ketchup will drop down.
The indicator is the diamond-shaped part that turns red in the selected item.
The label is the text, although you can use an image or bitmap as the label.
To create a new radiobutton widget as the child of a root window or frame named master:
w = Radiobutton ( master, option, ... )
This constructor returns the new radiobutton widget. Options:
activebackground The background color when the mouse is over the radiobutton. See Sec-
tion4.3, Colors (p. 6).
activeforeground The foreground color when the mouse is over the radiobutton.
anchor If the widget inhabits a space larger than it needs, this option specifies
where the radiobutton will sit in that space. The default is anchor=CEN-
TER. For other positioning options, see Section4.5, Anchors (p. 8). For
example, if you set anchor=NE, the radiobutton will be placed in the top
right corner of the available space.
bg or background The normal background color behind the indicator and label.
bitmap To display a monochrome image on a radiobutton, set this option to a
bitmap; see Section4.7, Bitmaps (p. 8).
borderwidth The size of the border around the indicator part itself. Default is 2 pixels.
For possible values, see Section4.1, Dimensions (p. 5).
command A procedure to be called every time the user changes the state of this ra-
diobutton.
cursor If you set this option to a cursor name (see Section4.8, Cursors (p. 9)),
the mouse cursor will change to that pattern when it is over the radiobut-
ton.
disabledforeground The foreground color used to render the text of a disabled radiobutton.
The default is a stippled version of the default foreground color.
font The font used for the text. See Section4.4, Type fonts (p. 6).
fg or foreground The color used to render the text.
height The number of lines (not pixels) of text on the radiobutton. Default is 1.
highlightbackground The color of the focus highlight when the radiobutton does not have focus.
See Section23, Focus: routing keyboard input (p. 74).
highlightcolor The color of the focus highlight when the radiobutton has the focus.
highlightthickness The thickness of the focus highlight. Default is 1. Set highlightthick-
ness=0 to suppress display of the focus highlight.
.deselect()
Clears (turns off) the radiobutton.
.flash()
Flashes the radiobutton a few times between its active and normal colors, but leaves it the way it
started.
.invoke()
You can call this method to get the same actions that would occur if the user clicked on the radiobut-
ton to change its state.
.select()
Sets (turns on) the radiobutton.
Each scale displays a slider that the user can drag along a trough to change the value. In the figure, the
first slider is currently at -0.38 and the second at 7.
You can drag the slider to a new value with mouse button 1.
If you click button 1 in the trough, the slider will move one increment in that direction per click.
Holding down button 1 in the trough will, after a delay, start to auto-repeat its function.
If the scale has keyboard focus, left arrow and up arrow keystrokes will move the slider up (for
vertical scales) or left (for horizontal scales). Right arrow and down arrow keystrokes will move the
slider down or to the right.
To create a new scale widget as the child of a root window or frame named master:
w = Scale ( master, option, ... )
activebackground The color of the slider when the mouse is over it. See Section4.3, Col-
ors (p. 6).
bg or background The background color of the parts of the widget that are outside the
trough.
bd or borderwidth Width of the 3-d border around the trough and slider. Default is 2 pixels.
For acceptable values, see Section4.1, Dimensions (p. 5).
command A procedure to be called every time the slider is moved. If the slider is
moved rapidly, you may not get a callback for every possible position,
but you'll certainly get a callback when it settles.
cursor The cursor that appears when the mouse is over the scale. See Section4.8,
Cursors (p. 9).
digits The way your program reads the current value shown in a scale widget
is through a control variable; see Section22, Control variables: the values
behind the widgets (p. 72). The control variable for a scale can be an
IntVar, a DoubleVar (float), or a StringVar. If it is a string variable,
the digits option controls how many digits to use when the numeric
scale value is converted to a string.
font The font used for the label and annotations. See Section4.4, Type
fonts (p. 6).
fg or foreground The color of the text used for the label and annotations.
from_ A float or integer value that defines one end of the scale's range. For ver-
tical scales, this is the top end; for horizontal scales, the left end. The un-
derbar (_) is not a typo: because from is a reserved word in Python, this
option is spelled from_. The default is 0. See the to option, below, for
the other end of the range.
highlightbackground The color of the focus highlight when the scale does not have focus. See
Section23, Focus: routing keyboard input (p. 74).
highlightcolor The color of the focus highlight when the scale has the focus.
highlightthickness The thickness of the focus highlight. Default is 1. Set highlightthick-
ness=0 to suppress display of the focus highlight.
label You can display a label within the scale widget by setting this option to
the label's text. The label appears in the top left corner if the scale is hori-
zontal, or the top right corner if vertical. The default is no label.
length The length of the scale widget. This is the x dimension if the scale is hori-
zontal, or the y dimension if vertical. The default is 100 pixels. For allow-
able values, see Section4.1, Dimensions (p. 5).
orient Set orient=HORIZONTAL if you want the scale to run along the x dimen-
sion, or orient=VERTICAL to run parallel to the y-axis. Default is hori-
zontal.
relief With the default relief=FLAT, the scale does not stand out from its
background. You may also use relief=SOLID to get a solid black frame
around the scale, or any of the other relief types described in Section4.6,
Relief styles (p. 8).
.get()
This method returns the current value of the scale.
.set ( value )
Sets the scale's value.
The slider, or scroll thumb, is the raised-looking rectangle that shows the current scroll position.
The two triangular arrowheads at each end are used for moving the position by small steps.
The trough is the sunken-looking area visible behind the arrowheads and slider.
Scrollbars can be horizontal, like the one shown above, or vertical. A widget that has two scrollable
dimensions, such as a canvas or listbox, can have both a horizontal and a vertical scrollbar.
The slider's size and position, relative to the length of the entire widget, show the size and position
of the view relative to its total size. For example, if a vertical scrollbar is associated with a listbox,
and its slider extends from 50% to 75% of the height of the scrollbar, that means that the visible part
of the listbox shows that portion of the overall list starting at the halfway mark and ending at the
three-quarter mark.
In a horizontal scrollbar, clicking B1 (button 1) on the left arrowhead moves the view by a small
amount to the left. Clicking B1 on the right arrowhead moves the view by that amount to the right.
For a vertical scrollbar, clicking the upward- and downward-pointing arrowheads moves the view
small amounts up or down. Refer to the discussion of the associated widget to find out the exact
amount that these actions move the view.
The user can drag the slider with B1 or B2 (the middle button) to move the view.
For a horizontal scrollbar, clicking B1 in the trough to the left of the slider moves the view left by a
page, and clicking B1 in the trough to the right of the slider moves the view a page to the right. For
a vertical scrollbar, the corresponding actions move the view a page up or down.
Clicking B2 anywhere along the trough moves the slider so that its left or top end is at the mouse,
or as close to it as possible.
To create a new scrollbar widget as the child of a root window or frame master:
w = Scrollbar ( master, option, ... )
The constructor returns the new scrollbar widget. Options for scrollbars include:
activebackground The color of the slider and arrowheads when the mouse is over them. See
Section4.3, Colors (p. 6).
bg or background The color of the slider and arrowheads when the mouse is not over them.
bd or borderwidth The width of the 3-d borders around the entire perimeter of the trough,
and also the width of the 3-d effects on the arrowheads and slider. Default
is no border around the trough, and a 2-pixel border around the arrow-
heads and slider.
command A procedure to be called whenever the scrollbar is moved. For a discussion
of the calling sequence, see Section16.1, The scrollbar command call-
back (p. 50).
cursor The cursor that appears when the mouse is over the scrollbar. See Sec-
tion4.8, Cursors (p. 9).
.get()
Returns two numbers (a, b) describing the current position of the slider. The a value gives the pos-
ition of the left or top edge of the slider, for horizontal and vertical scrollbars respectively; the b
value gives the position of the right or bottom edge. Each value is in the interval [0.0, 1.0] where 0.0
is the leftmost or top position and 1.0 is the rightmost or bottom position. For example, if the slider
extends from halfway to three-quarters of the way along the trough, you might get back the tuple
(0.5,0.75).
.set ( first, last )
To connect a scrollbar to another widget w, set w's xscrollcommand or yscrollcommand to the
scrollbar's .set method. The arguments have the same meaning as the values returned by the
.get() method. Please note that moving the scrollbar's slider does not move the corresponding
widget.
self.canv["xscrollcommand"] = self.scrollX.set
self.canv["yscrollcommand"] = self.scrollY.set
Notes:
The connection goes both ways. The canvas's xscrollcommand option has to be connected to the
horizontal scrollbar's .set method, and the scrollbar's command option has to be connected to the
canvas's .xview method. The vertical scrollbar and canvas must have the same mutual connection.
The sticky options on the .grid() method calls for the scrollbars force them to stretch just enough
to fit the corresponding dimension of the canvas.
To create a text widget as the child of a root window or frame named master:
w = Text ( master, option, ... )
The constructor returns the new text widget. Options include:
bg or background The default background color of the text widget. See Section4.3, Col-
ors (p. 6).
bd or borderwidth The width of the border around the text widget. Default is 2 pixels.
cursor The cursor that will appear when the mouse is over the text widget. See
Section4.8, Cursors (p. 9).
exportselection Normally, text selected within a text widget is exported to be the selection
in the window manager. Set exportselection=0 if you don't want
that behavior.
font The default font for text inserted into the widget. Note that you can have
multiple fonts in the widgets by using tags to change the properties of
some text. See Section4.4, Type fonts (p. 6).
fg or foreground The color used for text (and bitmaps) within the widget. You can change
the color for tagged regions; this option is just the default.
height The height of the widget in lines (not pixels!), measured according to the
current font size.
highlightbackground The color of the focus highlight when the text widget does not have focus.
See Section23, Focus: routing keyboard input (p. 74).
highlightcolor The color of the focus highlight when the text widget has the focus.
highlightthickness The thickness of the focus highlight. Default is 1. Set highlightthick-
ness=0 to suppress display of the focus highlight.
insertbackground The color of the insertion cursor. Default is black.
insertborderwidth Size of the 3-D border around the insertion cursor. Default is 0.
xscrollcommand To make the text widget horizontally scrollable, set this option to the
.set method of the horizontal scrollbar.
"line.column"
The position just before the given column (counting from zero) on the given line (counting from
one). Examples: "1.0" is the position of the beginning of the text; "2.3" is the position before the
fourth character of the second line.
"line.end"
The position just before the newline at the end of the given line (counting from one). So, for example,
index "10.end" is the position at the end of the tenth line.
INSERT
The position of the insertion cursor in the text widget.
CURRENT
The position of the character closest to the mouse pointer.
END
The position after the last character of the text.
SEL_FIRST
If some of the text in the widget is currently selection (as by dragging the mouse over it), this is the
position before the start of the selection. If you try to use this index and nothing is selected, a
TclError exception will be raised.
SEL_LAST
The position after the end of the selection, if any. As with SEL_FIRST, you'll get a TclError ex-
ception if you use such an index and there is no selection.
"markname"
You can use a mark as an index; just pass its name where an index is expected. See Section17.2,
Marks in text widgets (p. 53).
"tag.first"
The position before the first character of the region tagged with name tag; see Section17.5, Tags
in text widgets (p. 54).
"tag.last"
The position after the last character of a tagged region.
"@x,y"
The position before the character closest to the coordinate (x, y).
embedded-object
If you have an image or window embedded in the text widget, you can use the PhotoImage,
BitmapImage, or embedded widget as an index. See Section17.3, Images in text widgets (p. 54)
and Section17.4, Windows in text widgets (p. 54).
Refer to Section17.7, Methods on Text widgets (p. 55), below, to see how to use marks.
For example, setting tabs=("0.5i", "0.8i", RIGHT, "1.2i", CENTER, "2i", NUMERIC)
would set four tab stops: a left-aligned tab stop half an inch from the left side, a right-aligned tab
stop 0.8" from the left side, a center-aligned tab stop 1.2" from the left, and a numeric-aligned tab
stop 2" from the left.
backwards Set this option to 1 to search backwards from the index. Default is
forwards.
count If you set this option to an IntVar control variable, when there is a
match you can retrieve the length of the text that matched by using
the .get() method on that variable after the method returns.
regexp Set this option to 1 to interpret the pattern as a Tcl-style regular ex-
pression. The default is to look for an exact match to pattern. Tcl
.see ( index )
If the text containing the given index is not visible, scroll the text until that text is visible.
.tag_add ( tagName, index1, index2=None )
This method associates the tag named tagName with a region of the contents starting just after index
index1 and extending up to index index2. If you omit index2, only the character after index1
is tagged.
.tag_bind ( tagName, sequence, func, add=None )
This method binds an event to all the text tagged with tagName. See Section24, Events (p. 75),
below, for more information on event bindings.
To create a new binding for tagged text, use the first three arguments: sequence identifies the
event, and func is the function you want it to call when that event happens.
To add another binding to an existing tag, pass the same first three arguments and "+" as the fourth
argument.
To find out what bindings exist for a given sequence on a tag, pass only the first two arguments;
the method returns the associated function.
To find all the bindings for a given tag, pass only the first argument; the method returns a list of all
the tag's sequence arguments.
.tag_cget ( tagName, option )
Use this method to retrieve the value of the given option for the given tagName.
.tag_config ( tagName, option, ... )
To change the value of options for the tag named tagName, pass in one or more option=value
pairs.
If you pass only one argument, you will get back a dictionary defining all the options and their
values currently in force for the named tag.
Here are the options for tag configuration:
background The background color for text with this tag. Note that you can't use
bg as an abbreviation.
bgstipple To make the background appear grayish, set this option to one of the
standard bitmap names (see Section4.7, Bitmaps (p. 8)). This has
no effect unless you also specify a background.
borderwidth Width of the border around text with this tag. Default is 0. Note that
you can't use bd as an abbreviation.
fgstipple To make the text appear grayish, set this option a bitmap name.
font The font used to display text with this tag. See Section4.4, Type
fonts (p. 6).
foreground The color used for text with this tag. Note that you can't use the fg
abbreviation here.
.window_names()
Returns a sequence containing the names of all embedded widgets.
.xview ( MOVETO, fraction )
This method scrolls the text widget horizontally, and is intended for binding to the command option
of a related horizontal scrollbar.
This method can be called in two different ways. The first call positions the text at a value given by
fraction, where 0.0 moves the text to its leftmost position and 1.0 to its rightmost position.
.xview ( SCROLL, n, what )
The second call moves the text left or right: the what argument specifies how much to move and
can be either UNITS or PAGES, and n tells how many characters or pages to move the text to the
right relative to its image (or left, if negative).
.xview_moveto ( fraction )
This method scrolls the text in the same way as .xview(MOVETO, fraction).
.xview_scroll ( n, what )
Same as .xview(SCROLL, n, what).
.yview(MOVETO, fraction)
.yview(SCROLL, n, what)
.yview_moveto(fraction)
.yview_scroll(n, what)
These are the same as the .xview() and related methods, only for vertical scrolling. When scrolling
vertically by UNITS, the units are lines.
bg or background The background color of the window. See Section4.3, Colors (p. 6).
bd or borderwidth Border width in pixels; default is 0. For possible values, see Section4.1,
Dimensions (p. 5). See also the relief option, below.
class_ You can give a Toplevel window a class name. Such names are
matched against the option database, so your application can pick up the
user's configuration preferences (such as colors) by class name. For ex-
ample, you might design a series of popups called screamers, and set
them all up with class_="Screamer". Then you can put a line in your
option database like this:
*Screamer*background:
red
and then, if you use the .option_readfile() method to read your
option database, all widgets with that class name will default to a red
background. This option is named class_ because class is a reserved
word in Python.
cursor The cursor that appears when the mouse is in this window. See Section4.8,
Cursors (p. 9).
height Window height; see Section4.1, Dimensions (p. 5).
relief Normally, a top-level window will have no 3-d borders around it. To get
a shaded border, set the bd option larger that its default value of zero,
and set the relief option to one of the constants discussed under Sec-
tion4.6, Relief styles (p. 8).
width The desired width of the window; see Section4.1, Dimensions (p. 5).
w.destroy()
Calling w.destroy() on a widget w destroys w and all its children.
w.event_add ( virtual, *sequences )
This method creates a virtual event whose name is given by the virtual string argument. Each
additional argument describes one sequence, that is, the description of a physical event. When that
event occurs, the new virtual event is triggered.
See Section24, Events (p. 75) for a general description of virtual events.
w.event_delete ( virtual, *sequences )
Deletes physical events from the virtual event whose name is given by the string virtual. If all
the physical events are removed from a given virtual event, that virtual event won't happen anymore.
Higher-level priorities take precedence over lower-level ones. See Section20, Standardizing ap-
pearance (p. 69) for an overview of the option database. The syntax of the pattern argument to
.option_add() is the same as the option-pattern part of the resource specification line.
For example, to get the effect of this resource specification line:
*Button*font: times 24 bold
your application (self in this example) might include these lines:
self.bigFont = tkFont.Font ( family="times", size=24,
weight="bold" )
self.option_add ( "*Button*font", self.bigFont )
Any Button widgets created after executing these lines would default to bold Times 24 font (unless
overriden by a font option to the Button constructor).
w.option_clear()
This method removes all options from the Tkinter option database. This has the effect of going back
to all the default values.
w.option_get ( name, classname )
Use this method to retrieve the current value of an option from the Tkinter option database. The
first argument is the instance key and the second argument is the class key. If there are any matches,
it returns the value of the option that best matches. If there are no matches, it returns "".
Refer to Section20, Standardizing appearance (p. 69) for more about how keys are matched with
options.
Warning
The geometry is not accurate until the application has updated its idle tasks. In particular, all
geometries are initially "1x1+0+0" until the widgets and geometry manager have negotiated
their sizes and positions. See the .update_idletasks() method, above, in this section to
see how to insure that the widget's geometry is up to date.
w.winfo_height()
Returns the current height of w in pixels. See the remarks on geometry updating under
.winfo_geometry(), above.
w.winfo_id()
Returns an integer that uniquely identifies w within its top-level window. You will need this for the
.winfo_pathname() method, below.
w.winfo_ismapped()
This method returns true if w is mapped, false otherwise. A widget is mapped if it has been gridded
(or placed or packed, if you are using one of the other geometry managers) into its parent, and if
its parent is mapped, and so on up to the top-level window.
w.winfo_manager()
If w has not been gridded (or placed via one of the other geometry managers), this method returns
an empty string. If w has been gridded or otherwise placed, it returns a string naming the geometry
manager, such as "grid".
w.winfo_name()
This method returns w's name relative to its parent. See Section4.11, Window names (p. 12). Also
see .winfo_pathname(), below, to find out how to obtain a widget's path name.
Many widgets require you to use control variables, special objects that connect widgets together and
to your program, so that you can read and set properties of the widgets. Control variables will be
discussed in the next section.
.get()
Returns the current value of the variable.
.set ( value )
Changes the current value of the variable. If any widget options are slaved to this variable, those
widgets will be updated when the main loop next idles; see .update_idletasks() in Section19,
Universal widget methods (p. 62) for more information on controlling this update cycle.
Here are some comments on how control variables are used with specific widgets:
Button
You can set its textvariable to a StringVar. Anytime that variable is changed, the text on the
button will be updated to display the new value. This is not necessary unless the button's text is
actually going to change: use the text attribute if the button's label is static.
Checkbutton
Normally, you will set the widget's variable option to an IntVar, and that variable will be set
to 1 when the checkbutton is turned on and to 0 when it is turned off. However, you can pick different
values for those two states with the onvalue and offvalue options, respectively.
You can even use a StringVar as the checkbutton's variable, and supply string values for the
offvalue and onvalue. Here's an example:
self.spamVar = StringVar()
self.spamCB = Checkbutton ( self, text="Spam?",
variable=self.spamVar, onvalue="yes", offvalue="no" )
If this checkbutton is on, self.spamVar.get() will return the string "yes"; if the checkbutton
is off, that same call will return the string "no". Furthermore, your program can turn the checkbutton
on by calling .set("yes").
You can also the textvariable option of a checkbutton to a StringVar. Then you can change
the text label on that checkbutton using the .set() method on that variable.
Entry
Set its textvariable option to a StringVar. Use that variable's .get() method to retrieve the
text currently displayed in the widget. You can also the variable's .set() method to change the
text displayed in the widget.
Label
You can set its textvariable option to a StringVar. Then any call to the variable's .set()
method will change the text displayed on the label. This is not necessary if the label's text is static;
use the text attribute for labels that don't change while the application is running.
Menubutton
If you want to be able to change the text displayed on the menu button, set its textvariable option
to a StringVar and use that variable's .set() method to change the displayed text.
Many widgets are provided with an outline called the focus highlight that shows the user which
widget has the highlight. This is normally a thin black frame located just outside the widget's border
(if any). For widgets that don't normally have a focus highlight (specifically, frames, labels, and
menus), you can set the highlightthickness option to a nonzero value to make the focus highlight
visible.
You can also change the color of the focus highlight using the highlightcolor option.
Widgets of class Frame, Label, and Menu are not normally visited by the focus. However, you can
set their takefocus options to 1 to get them included in focus traversal. You can also take any
widget out of focus traversal by setting its takefocus option to 0.
The order in which the tab key traverses the widgets is:
For widgets that are children of the same parent, focus goes in the same order the widgets were
created.
For parent widgets that contain other widgets (such as frames), focus visits the parent widget first
(unless its takefocus option is 0), then it visits the child widgets, recursively, in the order they
were created.
To sum up: to set up the focus traversal order of your widgets, create them in that order. Remove widgets
from the traversal order by setting their takefocus options to 0, and for those whose default takefocus
option is 0, set it to 1 if you want to add them to the order.
The above describes the default functioning of input focus in Tkinter. There is another, completely dif-
ferent way to handle itlet the focus go wherever the mouse goes. Under Section19, Universal widget
methods (p. 62), refer to the .tk_focusFollowsMouse() method.
You can also add, change or delete the way any key on the keyboard functions inside any widget by
using event bindings. See Section24, Events (p. 75) for the details.
24.1.Levels of binding
You can bind a handler to an event at any of three levels:
1. Instance binding: You can bind an event to one specific widget. For example, you might bind the
PageUp key in a canvas widget to a handler that makes the canvas scroll up one page. To bind an
event of a widget, call the .bind() method on that widget (see Section19, Universal widget
methods (p. 62)).
For example, suppose you have a canvas widget named self.canv and you want to draw an orange
blob on the canvas whenever the user clicks the mouse button 2 (the middle button). To implement
this behavior:
self.canv.bind ( "<Button-2>", self.__drawOrangeBlob )
The first argument is a sequence descriptor that tells Tkinter that whenever the middle mouse button
goes down, it is to call the event handler named self.__drawOrangeBlob. (See Section24.6,
Writing your handler (p. 81), below, for an overview of how to write handlers such as .__dra-
wOrangeBlob()). Note that you omit the parentheses after the handler name, so that Python will
pass in a reference the handler instead of trying to call it right away.
2. Class binding: You can bind an event to all widgets of a class. For example, you might set up all
Button widgets to respond to middle mouse button clicks by changing back and forth between
English and Japanese labels. To bind an event to all widgets of a class, call the .bind_class()
method on any widget (see Section19, Universal widget methods (p. 62), above).
For example, suppose you have several canvases, and you want to set up mouse button 2 to draw
an orange blob in any of them. Rather than having to call .bind() for every one of them, you can
set them all up with one call something like this:
self.bind_class ( "Canvas", "<Button-2>",
self.__drawOrangeBlob )
3. Application binding: You can set up a binding so that a certain event calls a handler no matter what
widget has the focus or is under the mouse. For example, you might bind the PrintScrn key to all
the widgets of an application, so that it prints the screen no matter what widget gets that key. To
bind an event at the application level, call the .bind_all() method on any widget (see Section19,
Universal widget methods (p. 62)).
Here's how you might bind the PrintScrn key, whose key name is "Print":
self.bind_all ( "<Key-Print>", self.__printScreen )
24.2.Event sequences
Tkinter has a powerful and general method for allowing you to define exactly which events, both spe-
cific and general, you want to bind to handlers.
In general, an event sequence is a string containing one or more event patterns. Each event pattern describes
one thing that can happen. If there is more than one event pattern in a sequence, the handler will be
called only when all the patterns happen in that same sequence.
The general form of an event pattern is:
<[modifier-]...type[-detail]>
The entire pattern is enclosed inside <>.
Here are some examples to give you the flavor of event patterns:
24.3.Event types
The full set of event types is rather large, but a lot of them are not commonly used. Here are most of
the ones you'll need:
Activate A widget is changing from being inactive to being active. This refers to
changes in the state option of a widget such as a button changing from
inactive (grayed out) to active.
Button The user pressed one of the mouse buttons. The detail part specifies
which button.
ButtonRelease The user let up on a mouse button. This is probably a better choice in
most cases than the Button event, because if the user accidentally presses
the button, they can move it off the widget to avoid setting off the event.
Configure The user changed the size of a widget, for example by dragging a corner
or side of the window.
Deactivate A widget is changing from being active to being inactive. This refers to
changes in the state option of a widget such as a radiobutton changing
from active to inactive (grayed out).
Destroy A widget is being destroyed.
Enter The user moved the mouse pointer into a visible part of a widget. (This
is different than the enter key, which is a KeyPress event for a key whose
name is actually "return".)
Expose This event occurs whenever at least some part of your application or
widget becomes visible after having been covered up by another window.
FocusIn A widget got the input focus (see Section23, Focus: routing keyboard
input (p. 74) for a general introduction to input focus.) This can happen
either in response to a user event (like using the tab key to move focus
24.4.Event modifiers
The modifier names that you can use in event sequences include:
Alt True when the user is holding the alt key down.
Any This modifier generalizes an event type. For example, the event pattern
"<Any-KeyPress>" applies to the pressing of any key.
Control True when the user is holding the control key down.
Double Specifies two events happening close together in time. For example,
<Double-Button-1> describes two presses of button 1 in rapid succes-
sion.
Lock True when the user has pressed shift lock.
Shift True when the user is holding down the shift key.
Triple Like Double, but specifies three events in rapid succession.
You can use shorter forms of the events. Here are some examples:
"<1>" is the same as "<Button-1>".
"x" is the same as "<KeyPress-x>".
Note that you can leave out the enclosing "<>" for most single-character keypresses, but you can't do
that for the space character (whose name is "<space>") or the less-than (<) character (whose name is
"<less>").
24.5.Key names
The detail part of an event pattern for a KeyPress or KeyRelease event specifies which key you're
binding. (See the Any modifier, above, if you want to get all keypresses or key releases).
The table below shows several different ways to name keys. See Section24.6, Writing your hand-
ler (p. 81), below, for more information on Event objects, whose attributes will describe keys in these
same ways.
.char If the event was related to a KeyPress or KeyRelease for a key that
produces a regular ASCII character, this string will be set to that character.
(For special keys like delete, see the .keysym attribute, below.)
.height If the event was a Configure, this attribute is set to the widget's new
height in pixels.
.keysym For KeyPress or KeyRelease events involving a special key, this attrib-
ute is set to the key's string name, e.g., "Prior" for the PageUp key. See
Section24.5, Key names (p. 78) for a complete list of .keysym names.
.keysym_num For KeyPress or KeyRelease events, this is set to a numeric version of
the .keysym field. For regular keys that produce a single character, this
field is set to the integer value of the key's ASCII code. For special keys,
refer to Section24.5, Key names (p. 78).
.num If the event was related to a mouse button, this attribute is set to the button
number (1, 2, or 3).
.serial An integer serial number that is incremented every time the server pro-
cesses a client request. You can use .serial values to find the exact time
sequence of events: those with lower values happened sooner.
.time This attribute is set to an integer which has no absolute meaning, but is
incremented every millisecond. This allows your application to determine,
for example, the length of time between two mouse clicks.
.widget Always set to the widget that caused the event. For example, if the event
was a mouse click that happened on a canvas, this attribute will be the
actual Canvas widget.
.width If the event was a Configure, this attribute is set to the widget's new
width in pixels.
.x The x coordinate of the mouse at the time of the event, relative to the
upper left corner of the widget.
.y The y coordinate of the mouse at the time of the event, relative to the
upper left corner of the widget.
.x_root The x coordinate of the mouse at the time of the event, relative to the
upper left corner of the screen.
.y_root The y coordinate of the mouse at the time of the event, relative to the
upper left corner of the screen.
1 These lines define a new function handler that expects three arguments. The first argument is
the Event object passed to all event handlers, and the second and third arguments will be set to
their default valuesthe extra arguments we need to pass it.
This technique can be extended to supply any number of additional arguments to handlers.