Tkinter
Tkinter
4 reference: a
GUI for Python
John W. Shipman
2009-07-14 11:41
Abstract
Describes the Tkinter widget set for constructing graphical user interfaces (GUIs) in the Python
programming language.
This publication is available in Web form1 and also as a PDF document2. Please forward any
comments to tcc-doc@nmt.edu.
Table of Contents
1. What is Tkinter? ....................................................................................................................... 3
2. A minimal application .............................................................................................................. 3
3. Definitions .............................................................................................................................. 4
4. Layout management ................................................................................................................. 4
4.1. The .grid() method .................................................................................................... 5
4.2. Other grid management methods ................................................................................... 6
4.3. Configuring column and row sizes ................................................................................. 7
4.4. Making the root window resizeable ................................................................................ 7
5. Standard attributes ................................................................................................................... 8
5.1. Dimensions ................................................................................................................... 8
5.2. The coordinate system ................................................................................................... 9
5.3. Colors ........................................................................................................................... 9
5.4. Type fonts ..................................................................................................................... 9
5.5. Anchors ...................................................................................................................... 11
5.6. Relief styles ................................................................................................................. 11
5.7. Bitmaps ....................................................................................................................... 12
5.8. Cursors ....................................................................................................................... 12
5.9. Images ........................................................................................................................ 13
5.10. Geometry strings ........................................................................................................ 14
5.11. Window names ........................................................................................................... 15
5.12. Cap and join styles ..................................................................................................... 15
5.13. Dash patterns ............................................................................................................. 16
5.14. Matching stipple patterns ............................................................................................ 16
6. The Button widget ................................................................................................................ 17
7. The Canvas widget ................................................................................................................ 19
7.1. Canvas coordinates ...................................................................................................... 20
7.2. The Canvas display list ................................................................................................ 20
7.3. Canvas object IDs ........................................................................................................ 21
7.4. Canvas tags ................................................................................................................ 21
1
http://www.nmt.edu/tcc/help/pubs/tkinter/
2
http://www.nmt.edu/tcc/help/pubs/tkinter/tkinter.pdf
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 2.5 and Tkinter 8.4 running in the X Window system under Linux.
Your version may vary.
Pertinent references:
• An Introduction to Tkinter3 by Fredrik Lundh.
• Python and Tkinter Programming by John Grayson (Manning, 2000, ISBN 1-884777-81-3).
• Python 2.5 quick reference4: general information about the Python language.
We'll start by looking at the visible part of Tkinter: creating the widgets and arranging them on the
screen. Later we will talk about how to connect the face—the “front panel”—of the application to the
logic behind it.
2. A minimal application
Here is a trivial Tkinter program containing only a Quit button:
#!/usr/local/bin/python 1
from Tkinter import * 2
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
3
http://www.pythonware.com/library/tkinter/introduction/index.htm
4
http://www.nmt.edu/tcc/help/pubs/python/web/
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. Definitions
Before we proceed, let's define some of the common terms.
window
This term has different meanings in different contexts, but in general it refers to a rectangular area
somewhere on your display screen.
top-level window
A window that exists independently on your screen. It will be decorated with the standard frame
and controls for your system's desktop manager. You can move it around on your desktop. You
can generally resize it, although your application can prevent this
widget
The generic term for any of the building blocks that make up an application in a graphical user in-
terface. Examples of widgets: buttons, radiobuttons, text fields, frames, and text labels.
frame
In Tkinter, the Frame widget is the basic unit of organization for complex layouts. A frame is a
rectangular area that can contain other widgets.
child, parent
When any widget is created, a parent-child relationship is created. For example, if you place a text
label inside a frame, the frame is the parent of the label.
4. 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 table—a 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.
where Constructor is one of the widget classes like Button, Frame, and so on, and parent is the
parent widget in which this child widget is being constructed. All widgets have a .grid() method
that you can use to tell the geometry manager where to put it.
w.grid(option=value, ...)
This method registers a widget w with the grid geometry manager—if you don't do this, the widget will
exist internally, but it will not be visible on the screen.
Here are the options to the .grid() geometry management method:
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.
in_ To register w as a child of some widget w2, use in_=w2. The new parent w2 must be a
descendant of the parent widget used when w was created.
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 3–6 and
column numbers 2–6.
• If you do not provide a sticky attribute, the default behavior is to center the widget in the cell.
• You can position the widget in a corner of the cell by using sticky=NE (top right), SE (bottom right),
SW (bottom left), or NW (top left).
• You can position the widget centered against one side of the cell by using sticky=N (top center), E
(right center), S (bottom center), or W (left center).
• Use sticky=N+S to stretch the widget vertically but leave it centered horizontally.
• Use sticky=E+W to stretch it horizontally but leave it centered vertically.
• Use sticky=N+E+S+W to stretch the widget both horizontally and vertically to fill the cell.
• The other combinations will also work. For example, sticky=N+S+W will stretch the widget vertically
and place it against the west (left) wall.
minsize The column or row's minimum size in pixels. If there is nothing in the given column or
row, it will not appear, even if you use this option.
pad A number of pixels that will be added to the given column or row, over and above the
largest cell in the column or row.
weight To make a column or row stretchable, use this option and supply a value that gives the
relative weight of this column or row when distributing the extra space. For example, if
a widget w contains a grid layout, these lines will distribute three-fourths of the extra
space to the first column and one-fourth to the second column:
w.columnconfigure(0, weight=3)
w.columnconfigure(1, weight=1)
If this option is not used, the column or row will not stretch.
def createWidgets(self):
top=self.winfo_toplevel() 1
top.rowconfigure(0, weight=1) 2
top.columnconfigure(0, weight=1) 3
self.rowconfigure(0, weight=1) 4
self.columnconfigure(0, weight=1) 5
self.quit = Button ( self, text="Quit", command=self.quit )
self.quit.grid(row=0, column=0, 6
sticky=N+S+E+W)
1 The “top level window” is the outermost window on the screen. However, this window is not your
Application window—it is the parent of the Application instance. To get the top-level window,
call the .winfo_toplevel() method on any widget in your application; see Section 25, “Universal
widget methods” (p. 92).
2 This line makes row 0 of the top level window's grid stretchable.
3 This line makes column 0 of the top level window's grid stretchable.
4 Makes row 0 of the Application widget's grid stretchable.
5 Makes column 0 of the Application widget's grid stretchable.
6 The argument sticky=N+S+E+W makes the button expand to fill its cell of the grid.
There is one more change that must be made. In the constructor, change the second line as shown:
The argument sticky=N+S+E+W to self.grid() is necessary so that the Application widget will
expand to fill its cell of the top-level window's grid.
5. Standard attributes
Before we look at the widgets, let's take a look at how some of their common attributes—such as sizes,
colors and fonts—are specified.
• Each widget has a set of options that affect its appearance and behavior—attributes 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. You can retrieve the current setting of any option by using the widget's .cget() method.
See Section 25, “Universal widget methods” (p. 92) for more on these methods.
5.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.
c Centimeters
i Inches
m Millimeters
p Printer's points (about 1/72")
+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 Section 5.1, “Dimensions” (p. 8).
5.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.
• If you are running under the X Window System, you can use any of the X font names. For example,
the font named "-*-lucidatypewriter-medium-r-*-*-*-140-*-*-*-*-*-*" is the author's
favorite fixed-width font for onscreen use. Use the xfontsel program to help you select pleasing fonts.
To get a list of all the families of fonts available on your platform, call this function:
tkFont.families()
The return value is a list of strings. Note: You must create your root window before calling this function.
These methods are defined on all Font objects:
.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 ascender.
descent Number of pixels of height between the baseline and the bottom of the lowest ascender.
5.5. Anchors
The Tkinter package defines a number of anchor constants that you can use to control where items
are positioned relative to their context. For example, anchors can specify where a widget is located inside
a frame when the frame is bigger than the widget.
These constants are given as compass points, where north is up and west is to the left. We apologize to
our Southern Hemisphere readers for this Northern Hemisphere chauvinism5.
The anchor constants are shown in this diagram:
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.
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.
5
http://flourish.org/upsidedownmap/
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.
5.8. Cursors
There are quite a number of different mouse cursors available. Their names and graphics are shown
here. The exact graphic may vary according to your operating system.
arrow man
based_arrow_down middlebutton
based_arrow_up mouse
boat pencil
bogosity pirate
bottom_left_corner plus
bottom_right_corner question_arrow
bottom_side right_ptr
bottom_tee right_side
box_spiral right_tee
center_ptr rightbutton
circle rtl_logo
clock sailboat
coffee_mug sb_down_arrow
cross sb_h_double_arrow
cross_reverse sb_left_arrow
crosshair sb_right_arrow
dot sb_v_double_arrow
dotbox shuttle
double_arrow sizing
draft_large spider
draft_small spraycan
draped_box star
exchange target
fleur tcross
gobbler top_left_arrow
gumby top_left_corner
hand1 top_right_corner
hand2 top_side
heart top_tee
icon trek
iron_cross ul_angle
left_ptr umbrella
left_side ur_angle
left_tee watch
leftbutton xterm
ll_angle X_cursor
lr_angle
5.9. Images
There are three general methods for displaying graphic images in your Tkinter application.
• To display bitmap (two-color) images in the .xbm format, refer to Section 5.9.1, “The BitmapImage
class” (p. 14).
• To display full-color images in the .gif, .pgm, or .ppm format, see Section 5.9.2, “The PhotoImage
class” (p. 14).
PhotoImage ( file=f )
where f is the name of the image file. The constructor returns a value that can be used anywhere Tkinter
expects an image.
"wxh±x±y"
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.
6
http://www.nmt.edu/tcc/help/pubs/pil/
The constructor returns the new Button widget. Its options include:
The constructor returns the new Canvas widget. Supported options include:
bd or borderwidth Width of the border around the outside of the canvas; see Section 5.1, “Di-
mensions” (p. 8). The default is two pixels.
bg or background Background color of the canvas. Default is a light gray, about "#E4E4E4".
closeenough A float that specifies how close the mouse must be to an item to be con-
sidered inside it. Default is 1.0.
confine If true (the default), the canvas cannot be scrolled outside of the
scrollregion (see below).
cursor Cursor used in the canvas. See Section 5.8, “Cursors” (p. 12).
height Size of the canvas in the Y dimension. See Section 5.1, “Dimensions” (p. 8).
highlightbackground Color of the focus highlight when the widget does not have focus. See Sec-
tion 29, “Focus: routing keyboard input” (p. 105).
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.
The constructor returns the object ID of the new arc object on canvas C.
Point (x0, y0) is the top left corner and (x1, y1) the lower right corner of a rectangle into which the ellipse
is fit. If this rectangle is square, you get a circle.
The various options include:
activedash These options apply when the arc is in the ACTIVE state, that is, when
activefill the mouse is over the arc. For example, the activefill option specifies
the interior color when the arc is active. For option values, see dash,
activeoutline
activestipple
activewidth
dash Dash pattern for the outline. See Section 5.13, “Dash patterns” (p. 16).
dashoffset Dash pattern offset for the outline. See Section 5.13, “Dash pat-
terns” (p. 16).
disableddash These options apply when the arc's state is DISABLED.
disabledfill
disabledoutline
disabledoutlinestipple
disabledstipple
disabledwidth
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 behavior. You can also set this option to any color and the interior
of the arc will be filled with that color.
offset Stipple pattern offset for the interior of the arc. See Section 5.14,
“Matching stipple patterns” (p. 16).
outline The color of the border around the outside of the slice. Default is black.
outlineoffset Stipple pattern offset for the outline. See Section 5.14, “Matching stipple
patterns” (p. 16).
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 outlinestipple="".
start Starting angle for the slice, in degrees, measured from +x direction. If
omitted, you get the entire ellipse.
state This option is NORMAL by default. It may be set to HIDDEN to make the
arc invisible or to DISABLED to gray out the arc and make it unrespons-
ive to events.
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.
which returns the integer ID number of the image object for that canvas.
The x and y values are the reference point that specifies where the bitmap is placed.
Options include:
activebackground These options specify the background, bitmap, and foreground values
activebitmap when the bitmap is active, that is, when the mouse is over the bitmap.
activeforeground
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-
tion 5.5, “Anchors” (p. 11) 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 Section 5.7, “Bitmaps” (p. 12).
disabledbackground These options specify the background, bitmap, and foreground to be used
disabledbitmap when the bitmap's state is DISABLED.
disabledforeground
foreground The color that will appear where there are 1 values in the bitmap. The default
is foreground="black".
state By default, items are created with state=NORMAL. Use DISABLED to make
the item grayed out and unresponsive to events; use HIDDEN to make the
item invisible.
tags The tag or tags to be associated with the object, as a string or tuple of strings.
See Section 7.4, “Canvas tags” (p. 21).
This constructor returns the integer ID number of the image object for that canvas.
The image is positioned relative to point (x, y). Options include:
id = C.create_line ( x0, y0, x1, y1, ..., xn, yn, option, ... )
The line goes through the series of points (x0, y0), (x1, y1), … (xn, yn). Options include:
activedash These options specify the dash, fill, stipple, and width values to be used
activefill when the line is active, that is, when the mouse is over it.
activestipple
activewidth
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.
arrowshape A tuple (d1, d2, d3) that describes the shape of the arrowheads added by
the arrow option. Default is (8,10,3).
d2
d3
d1
capstyle You can specify the shape of the ends of the line with this option; see Section 5.12,
“Cap and join styles” (p. 15). The default option is BUTT.
dash To produce a dashed line, specify this option; see Section 5.13, “Dash pat-
terns” (p. 16). The default appearance is a solid line.
disabledstipple
disabledwidth
fill The color to use in drawing the line. Default is fill="black".
joinstyle For lines that are made up of more than one line segment, this option controls
the appearance of the junction between segments. For more details, see Sec-
tion 5.12, “Cap and join styles” (p. 15). The default style is ROUND
offset For stippled lines, the purpose of this option is to match the item's stippling
pattern with those of adjacent objects. See Section 5.14, “Matching stipple pat-
terns” (p. 16)..
smooth If true, the line is drawn as a series of parabolic splines fitting the point set. De-
fault is false, which renders the line as a set of straight segments.
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.
state Normally, line items are created in state NORMAL. Set this option to HIDDEN to
make the line invisible; set it to DISABLED to make it unresponsive to the mouse.
stipple To draw a stippled line, set this option to a bitmap that specifies the stippling
pattern, such as stipple="gray25". See Section 5.7, “Bitmaps” (p. 12) for the
possible values.
tags The tags to be associated with the object, as a sequence of strings. See Section 7.4,
“Canvas tags” (p. 21).
width The line's width. Default is 1 pixel. See Section 5.1, “Dimensions” (p. 8) for
possible values.
(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:
activedash These options specify the dash pattern, fill color, outline color, outline
activefill stipple pattern, interior stipple pattern, and outline width values to be
used when the oval is in the ACTIVE state, that is, when the mouse is
activeoutline over the oval. For option values, see dash, fill, outline, outlines-
activeoutlinestipple tipple, stipple, and width.
activestipple
activewidth
dash To produce a dashed border around the oval, set this option to a dash
pattern; see Section 5.13, “Dash patterns” (p. 16)
dashoffset When using the dash option, the dashoffset option is used to change
the alignment of the border's dash pattern relative to the oval. See
Section 5.14, “Matching stipple patterns” (p. 16).
disableddash These options specify the appearance of the oval when the item's state
disabledfill is DISABLED.
disabledoutline
disabledoutlinestipple
disabledstipple
disabledwidth
fill The default appearance of an oval's interior 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 Section 5.3, “Colors” (p. 9).
offset Stipple pattern offset of the interior. See Section 5.14, “Matching stipple
patterns” (p. 16).
outline The color of the border around the outside of the ellipse. Default is
outline="black".
outlineoffset Stipple pattern offset of the border. See Section 5.14, “Matching stipple
patterns” (p. 16).
stipple A bitmap indicating how the interior of the ellipse 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 Section 5.7, “Bitmaps” (p. 12).
outlinestipple Stipple pattern to be used for the border. For option values, see
stipple below.
state By default, oval items are created in state NORMAL. Set this option to
DISABLED to make the oval unresponsive to mouse actions. Set it to
HIDDEN to make the item invisible.
tags The tags to be associated with the object, as a sequence of strings. See
Section 7.4, “Canvas tags” (p. 21).
(x2,y2)
(x0,y0)
(x1,y1)
(x4,y4) (x3,y3)
activedash These options specify the appearance of the polygon when it is in the
activefill ACTIVE state, that is, when the mouse is over it. For option values, see
dash, fill, outline, outlinestipple, stipple, and width.
activeoutline
activeoutlinestipple
activestipple
activewidth
dash Use this option to produce a dashed border around the polygon. See
Section 5.13, “Dash patterns” (p. 16).
dashoffset Use this option to start the dash pattern at some point in its cycle other
than the beginning. See Section 5.13, “Dash patterns” (p. 16).
disableddash These options specify the appearance of the polygon when its state is
disabledfill DISABLED.
disabledoutline
disabledoutlinestipple
disabledstipple
disabledwidth
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 Section 5.3, “Colors” (p. 9).
This constructor returns the object ID of the rectangle on that canvas. Options include:
activedash These options specify the appearance of the rectangle when its state
activefill is ACTIVE, that is, when the mouse is on top of the rectangle. For option
values, refer to dash, fill, outline, outlinestipple, stipple,
activeoutline and width below.
activeoutlinestipple
activestipple
activewidth
dash To produce a dashed border around the rectangle, use this option to
specify a dash pattern. See Section 5.13, “Dash patterns” (p. 16).
dashoffset Use this option to start the border's dash pattern at a different point
in the cycle; see Section 5.13, “Dash patterns” (p. 16).
disableddash These options specify the appearance of the rectangle when its state
disabledfill is DISABLED.
disabledoutline
disabledoutlinestipple
disabledstipple
disabledwidth
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
Section 5.3, “Colors” (p. 9).
offset Use this option to change the offset of the interior stipple pattern. See
Section 5.14, “Matching stipple patterns” (p. 16).
outline The color of the border. Default is outline="black".
outlineoffset Use this option to adjust the offset of the stipple pattern in the outline;
see Section 5.14, “Matching stipple patterns” (p. 16).
outlinestipple Use this option to produce a stippled outline. The pattern is specified
by a bitmap; see Section 5.7, “Bitmaps” (p. 12).
state By default, rectangles are created in the NORMAL state. The state is
ACTIVE when the mouse is over the rectangle. Set this option to DIS-
ABLED to gray out the rectangle and make it unresponsive to mouse
events.
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 Section 5.7, “Bitmaps” (p. 12).
tags The tags to be associated with the object, as a sequence of strings. See
Section 7.4, “Canvas tags” (p. 21).
width Width of the border. Default is 1 pixel. Use width=0 to make the
border invisible. See Section 5.1, “Dimensions” (p. 8).
This returns the object ID of the text object on canvas C. Options include:
activefill The text color to be used when the text is active, that is, when the mouse is over
it. For option values, see fill below.
activestipple The stipple pattern to be used when the text is active. For option values, see
stipple below.
anchor The default is anchor=CENTER, meaning that the text is centered vertically and
horizontally around position (x, y). See Section 5.5, “Anchors” (p. 11) 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).
disabledfill The text color to be used when the text object's state is DISABLED. For option
values, see fill below.
disabledstipple The stipple pattern to be used when the text is disabled. For option values, see
stipple below.
fill The default text color is black, but you can render it in any color by setting the
fill option to that color. See Section 5.3, “Colors” (p. 9).
font If you don't like the default font, set this option to any font value. See Section 5.4,
“Type fonts” (p. 9).
justify For multi-line textual displays, this option controls how the lines are justified:
LEFT (the default), CENTER, or RIGHT.
offset The stipple offset to be used in rendering the text. For more information, see
Section 5.14, “Matching stipple patterns” (p. 16).
state By default, the text item's state is NORMAL. Set this option to DISABLED to make
in unresponsive to mouse events, or set it to HIDDEN to make it invisible.
stipple A bitmap indicating how the text will be stippled. Default is stipple="", which
means solid. A typical value would be stipple="gray25". See Section 5.7,
“Bitmaps” (p. 12).
tags The tags to be associated with the object, as a sequence of strings. See Section 7.4,
“Canvas tags” (p. 21).
text The text to be displayed in the object, as a string. Use newline characters ("\n")
to force line breaks.
width If you don't specify a width option, the text will be set inside a rectangle as long
as the longest line. However, you can also set the width option to a dimension,
and each line of the text will be broken into shorter lines, if necessary, or even
broken within words, to fit within the specified width. See Section 5.1, “Dimen-
sions” (p. 8).
This returns the object ID for the window object. Options include:
anchor The default is anchor=CENTER, meaning that the window is centered on the (x, y) position.
See Section 5.5, “Anchors” (p. 11) for the possible values. For example, if you specify an-
chor=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 Section 5.1, “Dimensions” (p. 8) for possible values.
state By default, window items are in the NORMAL state. Set this option to DISABLED to make the
window unresponsive to mouse input, or to HIDDEN to make it invisible.
tags The tags to be associated with the object, as a sequence of strings. See Section 7.4, “Canvas
tags” (p. 21).
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.
The indicator is the part of the checkbutton that shows its state, and the label is the text that appears beside
it.
• You will need to create a control variable, an instance of the IntVar class, so your program can query
and set the state of the checkbutton. See Section 28, “Control variables: the values behind the wid-
gets” (p. 103), below.
• You can also use event bindings to react to user actions on the checkbutton; see Section 30,
“Events” (p. 106), below.
activebackground Background color when the checkbutton is under the cursor. See Section 5.3,
“Colors” (p. 9).
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=CENTER.
See Section 5.5, “Anchors” (p. 11) for the allowable values. For example, 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
Section 5.3, “Colors” (p. 9). For the bitmap option, this specifies the color
displayed for 0-bits in the bitmap.
bitmap To display a monochrome image on a button, set this option to a bitmap;
see Section 5.7, “Bitmaps” (p. 12).
bd or borderwidth The size of the border around the indicator. Default is two pixels. For pos-
sible values, see Section 5.1, “Dimensions” (p. 8).
command A procedure to be called every time the user changes the state of this
checkbutton.
compound Use this option to display both text and a graphic, which may be either a
bitmap or an image, on the button. Allowable values describe the position
of the graphic relative to the text, and may be any of BOTTOM, TOP, LEFT,
RIGHT, or CENTER. For example, compound=LEFT would position the
graphic to the left of the text.
cursor If you set this option to a cursor name (see Section 5.8, “Cursors” (p. 12)),
the mouse cursor will change to that pattern when it is over the checkbutton.
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 Section 5.4, “Type fonts” (p. 9).
fg or foreground The color used to render the text. For the bitmap option, this specifies
the color displayed for 1-bits in the bitmap.
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 Section 29, “Focus: routing keyboard input” (p. 105).
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.
image To display a graphic image on the button, set this option to an image object.
See Section 5.9, “Images” (p. 13).
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; see Section 5.1, “Dimen-
sions” (p. 8). The default is two pixels.
cursor The cursor used when the mouse is within the entry widget; see Section 5.8,
“Cursors” (p. 12).
disabledbackground The background color to be displayed when the widget is in the DISABLED
state. For option values, see bg above.
disabledforeground The foreground color to be displayed when the widget is in the DISABLED
state. For option values, see fg below.
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.
font The font used for text entered in the widget by the user. See Section 5.4,
“Type fonts” (p. 9).
highlightbackground Color of the focus highlight when the widget does not have focus. See Sec-
tion 29, “Focus: routing keyboard input” (p. 105).
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-
tion 5.3, “Colors” (p. 9).
insertborderwidth By default, the insertion cursor is a simple rectangle. You can get the cursor
with the RAISED relief effect (see Section 5.6, “Relief styles” (p. 11)) 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).
if op == "scroll":
units = L[2]
self.entry.xview_scroll ( howMany, units )
elif op == "moveto":
self.entry.xview_moveto ( howMany )
bg or background The frame's background color. See Section 5.3, “Colors” (p. 9).
bd or borderwidth Width of the frame's border. The default is 0 (no border). For permitted
values, see Section 5.1, “Dimensions” (p. 8).
cursor The cursor used when the mouse is within the frame widget; see Section 5.8,
“Cursors” (p. 12).
height The vertical dimension of the new frame. This will be ignored unless you
also call .grid_propagate(0) on the frame; see Section 4.2, “Other grid
management methods” (p. 6).
activebackground Background color to be displayed when the mouse is over the widget.
activeforeground Foreground color to be displayed when the mouse is over the widget.
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 Section 5.5, “An-
chors” (p. 11). For example, if you use anchor=NW, the text would be posi-
tioned in the upper left-hand corner of the available space.
bg or background The background color of the label area. See Section 5.3, “Colors” (p. 9).
bitmap Set this option equal to a bitmap or image object and the label will display
that graphic. See Section 5.7, “Bitmaps” (p. 12) and Section 5.9, “Im-
ages” (p. 13).
bd or borderwidth Width of the border around the label; see Section 5.1, “Dimensions” (p. 8).
The default value is two pixels.
compound If you would like the Label widget to display both text and a graphic
(either a bitmap or an image), the compound option specifies the relative
orientation of the graphic relative to the text. Values may be any of LEFT,
There are no special methods for label widgets other than the common ones (see Section 25, “Universal
widget methods” (p. 92)).
Here is an example of a LabelFrame widget containing two Button widgets. Note that the label
“Important controls” interrupts the border. This widget illustrates the default GROOVE relief (see Sec-
tion 5.6, “Relief styles” (p. 11)) and the default 'nw' label anchor, which positions the label at the left
side of the top of the frame.
To create a new LabelFrame widget inside a root window or frame parent:
bg or background The background color to be displayed inside the widget; see Section 5.3,
“Colors” (p. 9).
bd or borderwidth Width of the border drawn around the perimeter of the widget; see Sec-
tion 5.1, “Dimensions” (p. 8). The default value is two pixels.
cursor Selects the cursor that appears when the mouse is over the widget; see Sec-
tion 5.8, “Cursors” (p. 12).
fg or foreground Color to be used for the label text.
height The vertical dimension of the new frame. This will be ignored unless you
also call .grid_propagate(0) on the frame; see Section 4.2, “Other grid
management methods” (p. 6).
highlightbackground Color of the focus highlight when the widget does not have focus.
highlightcolor The color of the focus highlight when the widget has focus.
highlightthickness Thickness of the focus highlight.
activestyle This option specifies the appearance of the active line. It may have any of
these values:
"underline"
The active line is underlined. This is the default option.
"dotbox"
The active line is enclosed in a dotted line on all four sides.
"none"
The active line is given no special appearance.
listCon.get()
state By default, a listbox is in the NORMAL state. To make the listbox unresponsive
to mouse events, set this option to DISABLED.
takefocus Normally, the focus will tab through listbox widgets. Set this option to 0 to
take the widget out of the sequence. See Section 29, “Focus: routing keyboard
input” (p. 105).
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 Section 13.1, “Scrolling a Listbox wid-
get” (p. 51) 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 Section 13.1, “Scrolling a Listbox wid-
get” (p. 51).
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.
.bbox ( index )
Returns the bounding box of the line specified by index as a 4-tuple (xoffset, yoffset,
width, height), where the upper left pixel of the box is at (xoffset, yoffset) and the
width and height are given in pixels. The returned width value includes only the part of the line
occupied by text.
lbox.selection_anchor(3)
lbox.selection_set(ANCHOR,5)
To create a menu widget, you must first have created a Menubutton, which we will call mb:
activebackground The background color that will appear on a choice when it is under the
mouse. See Section 5.3, “Colors” (p. 9).
activeborderwidth Specifies the width of a border drawn around a choice when it is under the
mouse. Default is 1 pixel. For possible values, see Section 5.1, “Dimen-
sions” (p. 8).
activeforeground The foreground color that will appear on a choice when it is under the mouse.
bg or background The background color for choices not under the mouse.
These methods are available on Menu objects. The ones that create choices on the menu have their own
particular options; see Section 14.1, “Menu item creation (coption) options” (p. 55).
.add ( kind, coption, ...)
Add a new element of the given kind as the next available choice in this menu. The kind argument
may be any of "cascade", "checkbutton", "command", "radiobutton", or "separator".
Depending on the kind argument, this method is equivalent to .add_cascade(),
.add_checkbutton(), and so on; refer to those methods below for details.
.add_cascade ( coption, ... )
Add a new cascade element as the next available choice in this menu. Use the menu option in this
call to connect the cascade to the next level's menu, an object of type Menu.
.add_checkbutton ( coption, ... )
Add a new checkbutton as the next available choice in self. The options allow you to set up the
checkbutton much the same way as you would set up a Checkbutton object; see Section 14.1, “Menu
item creation (coption) options” (p. 55).
.add_command ( coption, ... )
Add a new command as the next available choice in self. Use the label, bitmap, or image option
to place text or an image on the menu; use the command option to connect this choice to a procedure
that will be called when this choice is picked.
activebackground The background color when the mouse is over the menubutton. See Sec-
tion 5.3, “Colors” (p. 9).
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 Section 5.5, “Anchors” (p. 11). 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 Section 5.7, “Bitmaps” (p. 12).
bd or borderwidth Width of the border around the menubutton. Default is two pixels. For
possible values, see Section 5.1, “Dimensions” (p. 8).
compound If you specify both text and a graphic (either a bitmap or an image), this
option specifies where the graphic appears relative to the text. Possible
values are NONE (the default value), TOP, BOTTOM, LEFT, RIGHT, and
CENTER. For example, compound=RIGHT would position the graphic to
Here is a brief example showing the creation of a menubutton and its associated menu with two
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.
This constructor returns the new Message widget. Options may be any of these:
aspect Use this option to specify the ratio of width to height as a percentage. For
example, aspect=100 would give you a text message fit into a square;
with aspect=200, the text area would be twice as wide as high. The default
value is 150, that is, the text will be fit into a box 50% wider than it is high.
bg or background The background color behind the text; see Section 5.3, “Colors” (p. 9).
bd or borderwidth Width of the border around the widget; see Section 5.1, “Dimen-
sions” (p. 8). The default is two pixels. This option is visible only when
the relief option is not FLAT.
cursor Specifies the cursor that appears when the mouse is over the widget; see
Section 5.8, “Cursors” (p. 12).
The illustrations above shows an OptionMenu in two states. The left-hand example shows the widget
in its initial form. The right-hand example shows how it looks when the mouse has clicked on it and
dragged down to the "boat" choice.
This constructor returns the new OptionMenu widget. The variable is a StringVar instance (see
Section 28, “Control variables: the values behind the widgets” (p. 103)) that is associated with the widget,
and the remaining arguments are the choices to be displayed in the widget as strings.
The illustration above was created with this code snippet:
To find out which choice is currently selected in an OptionMenu widget, the .get() method on the
associated control variable will return that choice as a string.
• You may choose to display handles within the widget. A handle is a small square that the user can
drag with the mouse.
• You may choose to make sashes visible. A sash is a bar placed between the child widgets.
• A pane is the area occupied by one child widget.
To create a new PanedWindow widget as the child of a root window or frame named parent:
This constructor returns the new PanedWindow widget. Here are the options:
To add child widgets to a PanedWindow, create the child widgets as children of the parent PanedWindow,
but rather than using the .grid() method to register them, use the .add() method on the PanedWin-
dow.
Here are the methods on PanedWindow widgets.
.add ( child[, option=value] ... )
Use this method to add the given child widget as the next child of this PanedWindow. First create
the child widget with the PanedWindow as its parent widget, but do not call the .grid()
method to register it. Then call .add(child) and the child will appear inside the PanedWindow
in the next available position.
after Normally, when you .add() a new child to a PanedWindow, the new child is added after
any existing child widgets. You may instead use the after=w option to insert the new
widget at a position just after an existing child widget w.
• 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.
• If you prefer, you can dispense with the indicator. This makes the radiobuttons look like “push-push”
buttons, with the selected entry appearing sunken and the rest appearing raised.
• To form several radiobuttons into a functional group, create a single control variable (see Section 28,
“Control variables: the values behind the widgets” (p. 103), below), and set the variable option of
each radiobutton to that variable.
The control variable can be either an IntVar or a StringVar. If two or more radiobuttons share the
same control variable, setting any of them will clear the others.
• Each radiobutton in a group must have a unique value option of the same type as the control variable.
For example, a group of three radiobuttons might share an IntVar and have values of 0, 1, and 99.
Or you can use a StringVar control variable and give the radiobuttons value options like "too
hot", "too cold", and "just right".
To create a new radiobutton widget as the child of a root window or frame named parent:
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 ver-
tical 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 parent:
activebackground The color of the slider when the mouse is over it. See Section 5.3, “Col-
ors” (p. 9).
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 two pixels.
For acceptable values, see Section 5.1, “Dimensions” (p. 8).
command A procedure to be called every time the slider is moved. This procedure
will be passed one argument, the new scale value. If the slider is moved
.set ( value )
Sets the scale's value.
• 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, 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 one
on the left or top is called arrow1, and the one on the right or bottom is called arrow2.
• The trough is the sunken-looking area visible behind the arrowheads and slider. The trough is divided
into two areas named trough1 (above or to the left of the slider) and trough2 (below or to the right
of the slider).
• 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.
The normalized position of the scrollbar refers to a number in the closed interval [0.0, 1.0] that defines the
slider's position. For vertical scrollbars, position 0.0 is at the top and 1.0 at the bottom; for horizontal
scrollbars, position 0.0 is at the left end and 1.0 at the right.
To create a new Scrollbar widget as the child of a root window or frame parent:
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
Section 5.3, “Colors” (p. 9).
activerelief By default, the slider is shown with the RAISED relief style. To display the
slider with a different relief style when the mouse is over the slider.
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 two-pixel border around the arrowheads
and slider. For possible values, see Section 5.1, “Dimensions” (p. 8).
command A procedure to be called whenever the scrollbar is moved. For a discussion
of the calling sequence, see Section 21.1, “The Scrollbar command call-
back” (p. 71).
cursor The cursor that appears when the mouse is over the scrollbar. See Section 5.8,
“Cursors” (p. 12).
elementborderwidth The width of the borders around the arrowheads and slider. The default is
elementborderwidth=-1, which means to use the value of the border-
width option.
highlightbackground The color of the focus highlight when the scrollbar does not have focus. See
Section 29, “Focus: routing keyboard input” (p. 105).
highlightcolor The color of the focus highlight when the scrollbar has the focus.
highlightthickness The thickness of the focus highlight. Default is 1. Set to 0 to suppress display
of the focus highlight.
jump This option controls what happens when a user drags the slider. Normally
(jump=0), every small drag of the slider causes the command callback to
be called. If you set this option to 1, the callback isn't called until the user
releases the mouse button.
orient Set orient=HORIZONTAL for a horizontal scrollbar, orient=VERTICAL
for a vertical one (the default orientation).
relief Controls the relief style of the widget; the default style is SUNKEN. This
option has no effect in Windows.
repeatdelay This option controls how long button 1 has to be held down in the trough
before the slider starts moving in that direction repeatedly. Default is re-
peatdelay=300, and the units are milliseconds.
repeatinterval This option controls how often slider movement will repeat when button
1 is held down in the trough. Default is repeatinterval=100, and the
units are milliseconds.
takefocus Normally, you can tab the focus through a scrollbar widget; see Section 29,
“Focus: routing keyboard input” (p. 105). Set takefocus=0 if you don't
want this behavior. The default key bindings for scrollbars allow the user
to use the ← and → arrow keys to move horizontal scrollbars, and they can
use the ↑ and ↓ keys to move vertical scrollbars.
troughcolor The color of the trough.
• When the user requests a movement of one unit right or down, the arguments are:
command("scroll", 1, "pages")
• When the user drags the slider to a value f in the range [0,1], where 0 means all the way left or up
and 1 means all the way right or down, the call is:
command("moveto", f)
These calling sequences match the arguments expected by the .xview() and .yview() methods of
canvases, listboxes, and text widgets. The Entry widget does not have an .xview() method. See
Section 9.1, “Scrolling an Entry widget” (p. 43).
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.
activebackground Background color when the cursor is over the widget; see Section 5.3,
“Colors” (p. 9).
bg or background Background color of the widget.
bd or borderwidth Width of the border around the widget; see Section 5.1, “Dimen-
sions” (p. 8). The default value is one pixel.
buttonbackground The background color displayed on the arrowheads. The default is gray.
buttoncursor The cursor to be displayed when the mouse is over the arrowheads; see
Section 5.8, “Cursors” (p. 12).
buttondownrelief The relief style for the downward-pointing arrowhead; see Section 5.6,
“Relief styles” (p. 11). The default style is RAISED.
buttonup The relief style for the upward-pointing arrowhead; see Section 5.6, “Relief
styles” (p. 11). The default style is RAISED.
command Use this option to specify a function or method to be called whenever the
user clicks on one of the arrowheads. Note that the callback is not called
when the user edits the value directly as if it were an Entry.
cursor Selects the cursor that is displayed when the mouse is over the entry part
of the widget; see Section 5.8, “Cursors” (p. 12).
disabledbackground These options select the background and foreground colors displayed when
disabledforeground the widget's state is DISABLED.
exportselection Normally, the text in the entry portion of a Spinbox can be cut and pasted.
To prohibit this behavior, set the exportselection option to True.
font Use this option to select a different typeface for the entry text; see Section 5.4,
“Type fonts” (p. 9).
autoseparators If the undo option is set, the autoseparators option controls whether
separators are automatically added to the undo stack after each insertion or
deletion (if autoseparators=True) or not (if autoseparators=False).
For an overview of the undo mechanism, see Section 23.7, “The Text widget
undo/redo stack” (p. 82).
bg or background The default background color of the text widget. See Section 5.3, “Col-
ors” (p. 9).
bd or borderwidth The width of the border around the text widget; see Section 5.1, “Dimen-
sions” (p. 8). The default is two pixels.
cursor The cursor that will appear when the mouse is over the text widget. See
Section 5.8, “Cursors” (p. 12).
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 Section 5.4, “Type fonts” (p. 9).
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.
xscrollcommand To make the text widget horizontally scrollable, set this option to the .set
method of the horizontal scrollbar.
yscrollcommand To make the text widget vertically scrollable, set this option to the .set
method of the vertical scrollbar.
abcdef
The index expression “1.0 + 5 chars” refers to the position between e and f. You can omit
blanks and abbreviate keywords in these expressions if the result is unambiguous. This example
could be abbreviated “1.0+5c”.
- n chars
Similar to the previous form, but the position moves backwards n characters.
+ n lines
Moves n lines past the given index. Tkinter tries to leave the new position in the same column as it
was on the line it left, but if the line at the new position is shorter, the new position will be at the
end of the line.
- n lines
Moves n lines before the given index.
linestart
Moves to the position before the first character of the given index. For example, position “current
linestart” refers to the beginning of the line closest to the mouse pointer.
lineend
Moves to the position after the last character of the given index. For example, position “sel.last
lineend” refers to the end of the line containing the end of the current selection.
wordstart
The position before the beginning of the word containing the given index. For example, index
“11.44 wordstart” refers to the position before the word containing position 44 on line 11.
For the purposes of this operation, a word is either a string of consecutive letter, digit, or underbar
(_) characters, or a single character that is none of these types.
align This option specifies how the image is to be aligned vertically if its height is less than the
height of its containing line. Values may be top to align it at the top of its space; center
to center it; bottom to place it at the bottom; or baseline to line up the bottom of the
image with the text baseline.
image The image to be used. See Section 5.9, “Images” (p. 13).
name You can assign a name to this instance of the image. If you omit this option, Tkinter will
generate a unique name. If you create multiple instances of an image in the same Text
widget, Tkinter will generate a unique name by appending a “#” followed by a number.
padx If supplied, this option is a number of pixels of extra space to be added on both sides of
the image.
pady If supplied, this option is a number of pixels of extra space to be added above and below
the image.
backwards Set this option to True 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.
exact Set this option to True to search for text that exactly matches the pattern. This is
the default option. Compare the regexp option below.
forwards Set this option to True to search forwards from the index. This is the default option.
regexp Set this option to True to interpret the pattern as a Tcl-style regular expression.
The default is to look for an exact match to pattern. Tcl regular expressions are a
subset of Python regular expressions, supporting these features: . ^ [c1…] (…)
* + ? e1|e2
nocase Set this option to 1 to ignore case. The default is a case-sensitive search.
stopindex To limit the search, set this option to the index beyond which the search should not
go.
.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 Section 30, “Events” (p. 106),
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.
background The background color for text with this tag. Note that you can't use bg as an ab-
breviation.
bgstipple To make the background appear grayish, set this option to one of the standard
bitmap names (see Section 5.7, “Bitmaps” (p. 12)). 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 Section 5.4, “Type fonts” (p. 9).
foreground The color used for text with this tag. Note that you can't use the fg abbreviation
here.
justify The justify option set on the first character of each line determines how that
line is justified: LEFT (the default), CENTER, or RIGHT.
lmargin1 How much to indent the first line of a chunk of text that has this tag. The default
is 0. See Section 5.1, “Dimensions” (p. 8)for allowable values.
lmargin2 How much to indent successive lines of a chunk of text that has this tag. The de-
fault is 0.
offset How much to raise (positive values) or lower (negative values) text with this tag
relative to the baseline. Use this to get superscripts or subscripts, for example.
For allowable values, see Section 5.1, “Dimensions” (p. 8).
overstrike Set overstrike=1 to draw a horizontal line through the center of text with this
tag.
relief Which 3-D effect to use for text with this tag. The default is relief=FLAT; for
other possible values see Section 5.6, “Relief styles” (p. 11).
rmargin Size of the right margin for chunks of text with this tag. Default is 0.
spacing1 This option specifies how much extra vertical space is put above each line of text
with this tag. If a line wraps, this space is added only before the first line it occupies
on the display. Default is 0.
spacing2 This option specifies how much extra vertical space to add between displayed
lines of text with this tag when a logical line wraps. Default is 0.
spacing3 This option specifies how much extra vertical space is added below each line of
text with this tag. If a line wraps, this space is added only after the last line it oc-
cupies on the display. Default is 0.
tabs How tabs are expanded on lines with this tag. See Section 23.6, “Setting tabs in a
Text widget” (p. 82).
underline Set underline=1 to underline text with this tag.
wrap How long lines are wrapped in text with this tag. See the description of the wrap
option for text widgets, above.
align Specifies how to position the embedded widget vertically in its line, if it isn't as tall as
the text on the line. Values include: align=CENTER (the default), which centers the
widget vertically within the line; align=TOP, which places the top of the image at the
top of the line; align=BOTTOM, which places the bottom of the image at the bottom
of the line; and align=BASELINE, which aligns the bottom of the image with the text
baseline.
create A procedure that will create the embedded widget on demand. This procedure takes
no arguments and must create the widget as a child of the text widget and return the
widget as its result.
padx Extra space added to the left and right of the widget within the text line. Default is 0.
pady Extra space added above and below the widget within the text line. Default is 0.
stretch This option controls what happens when the line is higher than the embedded widget.
Normally this option is 0, meaning that the embedded widget is left at its natural size.
If you set stretch=1, the widget is stretched vertically to fill the height of the line,
and the align option is ignored.
window The widget to be embedded. This widget must be a child of the text widget.
.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)
The vertical scrolling equivalent of .xview(MOVETO,…).
.yview(SCROLL, n, what)
The vertical scrolling equivalent of .xview(SCROLL,…). When scrolling vertically by UNITS, the
units are lines.
Options include:
bg or background The background color of the window. See Section 5.3, “Colors” (p. 9).
bd or borderwidth Border width in pixels; default is 0. For possible values, see Section 5.1,
“Dimensions” (p. 8). 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 example, you
might design a series of pop-ups 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 Section 5.8,
“Cursors” (p. 12).
height Window height; see Section 5.1, “Dimensions” (p. 8).
highlightbackground The color of the focus highlight when the window does not have focus. See
Section 29, “Focus: routing keyboard input” (p. 105).
highlightcolor The color of the focus highlight when the window has the focus.
highlightthickness The thickness of the focus highlight. Default is 1. Set highlightthick-
ness=0 to suppress display of the focus highlight.
menu To provide this window with a top-level menubar, supply a Menu widget
as the value of this option. Under MacOS, this menu will appear at the top
of the screen when the window is active. Under Windows or Unix, it will
appear at the top of the application.
padx Use this option to provide extra space on the left and right sides of the
window. The value is a number of pixels.
pady Use this option to provide extra space on the top and bottom sides of the
window. The value is a number of pixels.
7
http://docs.python.org/library/time.html
w[option] = value
If you call the .config() method on a widget with no arguments, you'll get a dictionary of all the
widget's current options. The keys are the option names (including aliases like bd for borderwidth).
The value for each key is:
• for most entries, a five-tuple: (option name, option database key, option database class, default
value, current value); or,
• for alias names (like "fg"), a two-tuple: (alias name, equivalent standard name).
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 Section 30, “Events” (p. 106) for a general description of virtual events.
Higher-level priorities take precedence over lower-level ones. See Section 26, “Standardizing ap-
pearance” (p. 100) 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:
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 Section 26, “Standardizing appearance” (p. 100) for more about how keys are matched with
options.
w.option_readfile ( fileName, priority=None )
As a convenience for user configuration, you can designate a named file where users can put their
preferred options, using the same format as the .Xdefaults file. Then, when your application is
initializing, you can pass that file's name to this method, and the options from that file will be added
to the database. If the file doesn't exist, or its format is invalid, this method will raise TclError.
Refer to Section 26, “Standardizing appearance” (p. 100) for an introduction to the options database
and the format of option files.
w.quit()
This method exits the main loop. See .mainloop(), above, for a discussion of main loops.
w.rowconfigure()
See Section 4.2, “Other grid management methods” (p. 6).
w.selection_clear()
If w currently has a selection (such as a highlighted segment of text in an entry widget), clear that
selection.
w.selection_get()
If w currently has a selection, this method returns the selected text. If there is no selection, it raises
TclError.
w.selection_own()
Make w the owner of the selection in w's display, stealing it from the previous owner, if any.
w.selection_own_get()
Returns the widget that currently owns the selection in w's display. Raises TclError if there is no
such selection.
w.tk_focusFollowsMouse()
Normally, the input focus cycles through a sequence of widgets determined by their hierarchy and
creation order; see Section 29, “Focus: routing keyboard input” (p. 105). You can, instead, tell Tkinter
to force the focus to be wherever the mouse is; just call this method. There is no easy way to undo
it, however.
w.tk_focusNext()
Returns the widget that follows w in the focus traversal sequence. Refer to Section 29, “Focus:
routing keyboard input” (p. 105) for a discussion of focus traversal.
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 posi-
tions. 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. You may prefer to use .winfo_reqheight(), described below,
which is always up to date.
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 for w: this value will be one of "grid", "pack", "place", "canvas", or "text".
w.winfo_name()
This method returns w's name relative to its parent. See Section 5.11, “Window names” (p. 15). Also
see .winfo_pathname(), below, to find out how to obtain a widget's path name.
w.winfo_parent()
Returns w's parent's path name, or an empty string if w is a top-level window. See Section 5.11,
“Window names” (p. 15) above, for more on widget path names.
w.winfo_pathname ( id, displayof=0 )
If the displayof argument is false, returns the window path name of the widget with unique
identifier id in the application's main window. If displayof is true, the id number specifies a
widget in the same top-level window as w. See Section 5.11, “Window names” (p. 15) for a discussion
of widget path names.
w.winfo_pixels ( number )
For any dimension number (see Dimensions, above), this method returns that distance in pixels on
w's display, as an integer.
w.winfo_pointerx()
Returns the same value as the x coordinate returned by .winfo_pointerxy().
w.winfo_pointerxy()
Returns a tuple (x, y) containing the coordinates of the mouse pointer relative to w's root window.
If the mouse pointer isn't on the same screen, returns (-1, -1).
w.winfo_pointery()
Returns the same value as the y coordinate returned by .winfo_pointerxy().
class Jukebox(Frame):
def __init__(self, master):
"Constructor for the Jukebox class"
Frame.__init__ ( self, master, class_="Jukebox" )
self.__createWidgets()
...
The first form sets options only when the name of the application matches app; the second form sets
options for all applications.
For example, if your application is called xparrot, a line of the form
xparrot*background: LimeGreen
sets all background options in the xparrot application to lime green. (Use the -name option on the
command line when launching your application to set the name to "xparrot".)
The option-pattern part has this syntax:
{{*|.}name}...option
That is, each option-pattern is a list of zero or more names, each of which is preceded by an asterisk
or period. The last name in the series is the name of the option you are setting. Each of the rest of the
names can be either:
• the name of a widget class (capitalized), or
• the name of an instance (lowercased).
*font: times 24
This line says that all font options should default to 24-point Times. The * is called the loose binding
symbol, and means that this option pattern applies to any font option anywhere in any application.
Compare this example:
*Listbox.font: lucidatypewriter 14
The period between Listbox and font is called the tight binding symbol, and it means that this rule
applies only to font options for widgets in class Listbox.
As another example, suppose your xparrot application has instances of widgets of class Jukebox. In
order to set up a default background color for all widgets of that class Jukebox, you could put a line
in your options file like this:
xparrot*Jukebox*background: PapayaWhip
The loose-binding (*) symbol between Jukebox and background makes this rule apply to any
background attribute of any widget anywhere inside a Jukebox. Compare this option line:
xparrot*Jukebox.background: NavajoWhite
This rule will apply to the frame constituting the Jukebox widget itself, but because of the tight-binding
symbol it will not apply to widgets that are inside the Jukebox widget.
In the next section we'll talk about how Tkinter figures out exactly which option value to use if there
are multiple resource specification lines that apply.
*background: LimeGreen
*Listbox*background: FloralWhite
Both specifications apply to the background option in a Listbox widget, but the second one is more
specific, so it will win.
In general, the names in a resource specification are a sequence n1, n2, n3, ..., o where each ni is a class
or instance name. The class names are ordered from the highest to the lowest level, and o is the name
of an option.
However, when Tkinter is creating a widget, all it has is the class name and the instance name of that
widget.
Here are the precedence rules for resource specifications:
1. The name of the option must match the o part of the option-pattern. For example, if the rule is
xparrot*indicatoron: 0
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.
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 Section 30.6,
“Writing your handler: The Event class” (p. 112), below, for an overview of how to write handlers
such as .__drawOrangeBlob()). 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 Section 25, “Universal widget methods” (p. 92), 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:
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 Section 25,
“Universal widget methods” (p. 92)).
Here's how you might bind the PrintScrn key, whose “key name” is "Print":
<[modifier-]...type[-detail]>
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.
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>").
8
http://www.tcl.tk/man/tcl8.4/TkCmd/keysyms.htm
And as a method:
The attributes of the Event object passed to the handler are described below. Some of these attributes
are always set, but some are set only for certain types of events.
.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.)
.delta For MouseWheel events, this attribute contains an integer whose sign is positive to
scroll up, negative to scroll down. Under Windows, this value will be a multiple of
120; for example, 120 means scroll up one step, and -240 means scroll down two steps.
Under MacOS, it will be a multiple of 1, so 1 means scroll up one step, and -2 means
scroll down two steps. For Linux mouse wheel support, see the note on the Button
event binding in Section 30.3, “Event types” (p. 108).
Use these masks to test the bits of the .state value to see what modifier keys and buttons were pressed
during the event:
Mask Modifier
0x0001 Shift.
0x0002 Caps Lock.
0x0004 Control.
0x0008 Left-hand Alt.
Here's an example of an event handler. Under Section 30.1, “Levels of binding” (p. 107), above, there is
an example showing how to bind mouse button 2 clicks on a canvas named self.canv to a handler
called self.__drawOrangeBlob(). Here is that handler:
When this handler is called, the current mouse position is (event.x, event.y). The .cre-
ate_oval() method draws a circle whose bounding box is square and centered on that position and
has sides of length 2*r.
But event handlers are passed only one argument, the event. So we can't use the function above because
of a mismatch in the number of arguments.
Fortunately, Python's ability to provide default values for function arguments gives us a way out. Have
a look at this code:
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 values—the extra arguments we need to pass it.
This technique can be extended to supply any number of additional arguments to handlers.
You can then use "<<panic>>" in any event sequence. For example, if you use this call:
w.bind ( "<<panic>>", h )
any mouse button 3 or pause keypress in widget w will trigger the handler h.
See .event_add(), .event_delete(), and .event_info() under Section 25, “Universal widget
methods” (p. 92) for more information about creating and managing virtual events.
In each case, the title is a string to be displayed in the top of the window decoration. The message
argument is a string that appears in the body of the pop-up window; within this string, lines are broken
at newline ("\n") characters.
The option arguments may be any of these choices.
default
Which button should be the default choice? If you do not specify this option, the first button (“OK”,
“Yes”, or “Retry”) will be the default choice.
To specify whith button is the default choice, use default=C, where C is one of these constants
defined in tkMessageBox: CANCEL, IGNORE, OK, NO, RETRY, or YES.
icon
Selects which icon appears in the pop-up. Use an argument of the form icon=I where I is one of
these constants defined in tkMessageBox: ERROR, INFO, QUESTION, or WARNING.
parent
If you don't specify this option, the pop-up appears above your root window. To make the pop-up
appear above some child window W, use the argument parent=W.
Each of the “ask...” pop-up functions returns a value that depends on which button the user pushed
to remove the pop-up.
• askokcancel, askretrycancel, and askyesno all return a bool value: True for “OK” or “Yes”
choices, False for “No” or “Cancel” choices.
• askquestion returns u"yes" for “Yes”, or u"no" for “No”.
Arguments are:
color
The initial color to be displayed. The default initial color is a light gray.
title=text
The specified text appears in the pop-up window's title area. The default title is “Color”.
parent=W
Make the popup appear over window W. The default behavior is that it appears over your root
window.
If the user clicks the OK button on the pop-up, the returned value will be a tuple (triple, color),
where triple is a tuple (R, G, B) containing red, green, and blue values in the range [0,255] respect-
ively, and color is the selected color as a regular Tkinter color object.
If the users clicks Cancel, this function will return (None, None).
Here's what the popup looks like on the author's system: