Tkinter Reference
Tkinter Reference
Python
Contents
Part I: The face of your application
. . . . . . . . . . . . . . . . . . . . . . . . . 3
1. A minimal application . . . . . . . . . . .
2. Layout management . . . . . . . . . . . .
2.1 The .grid() method . . . . . . . .
2.2 Other grid management methods . . .
3. Standard attributes . . . . . . . . . . . . .
3.1 Dimensions . . . . . . . . . . . .
3.2 Coordinate system . . . . . . . . .
3.3 Colors . . . . . . . . . . . . . . .
3.4 Fonts . . . . . . . . . . . . . . .
3.5 Bitmaps . . . . . . . . . . . . . .
3.6 Cursors . . . . . . . . . . . . . .
3.7 Images . . . . . . . . . . . . . . .
4. The Button widget . . . . . . . . . . . . .
5. The Canvas widget . . . . . . . . . . . . .
5.1 The canvas arc object . . . . . . . .
5.2 The canvas bitmap object . . . . . . .
5.3 The canvas image object . . . . . . .
5.4 The canvas line object . . . . . . . .
5.5 The canvas oval object . . . . . . . .
5.6 The canvas polygon object . . . . . .
5.7 The canvas rectangle object . . . . . .
5.8 The canvas text object . . . . . . . .
5.9 The canvas window object . . . . . .
6. The Checkbutton widget . . . . . . . . . .
7. The Entry widget . . . . . . . . . . . . .
7.1 Scrolling an Entry widget . . . . . .
8. The Frame widget . . . . . . . . . . . . .
9. The Label widget . . . . . . . . . . . . .
10. The Listbox widget . . . . . . . . . . . .
10.1 Scrolling a Listbox widget . . . . .
11. The Menu widget . . . . . . . . . . . . .
12. The Menubutton widget . . . . . . . . . .
13. The Radiobutton widget . . . . . . . . .
14. The Scale widget . . . . . . . . . . . . .
15. The Scrollbar widget . . . . . . . . . . .
15.1 The scrollbar command callback . . .
15.2 Connecting scrollbars to other widgets
16. The Text widget . . . . . . . . . . . . .
16.1 Indices in text widgets . . . . . . .
New Mexico Tech Computer Center
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
3
3
4
5
6
6
6
7
7
8
9
9
10
11
17
18
18
19
19
20
21
22
22
23
26
28
28
29
31
34
34
38
40
43
46
48
49
49
50
Page 1
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
50
51
51
51
52
60
61
69
70
70
70
72
. . . . . . . . . . . . . . 73
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
73
75
76
77
78
78
79
80
82
83
84
Tkinter is a GUI widget set for Python. This document contains only the commoner
features. For complete documentation, see:
http://www.pythonware.com/library.htm
or the book Python and Tkinter Programming by John Grayson (Manning, 2000, ISBN
1-884777-81-3).
This document applies to Python 1.5 and Tkinter 8.0.4 running in the X Window system
under Linux. Your version may vary.
Refer to the authors companion publication, Python language quick reference, or to Web
site http://www.python.org/, for general information about the Python language.
Page 2
1. A minimal application
Here is a trivial Tkinter program containing only a Quit button:
#!/usr/local/bin/python
from Tkinter import *
# Interface to Tk widgets
class Application(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.grid()
self.createWidgets()
def createWidgets(self):
self.quitButton = Button ( self, text="Quit",
command=self.quit )
self.quitButton.grid()
app = Application()
# Instantiate the application class
app.master.title("Sample application")
app.mainloop()
# Wait for events
2. Layout management
Later we will discuss the widgets, the building blocks of your GUI application. How do
widgets get arranged in a window?
Although there are three different geometry managers in Tkinter, the author strongly
prefers the Grid geometry manager for pretty much everything. This manager treats
every window or frame as a tablea gridwork of rows and columns.
A cell is the area at the intersection of one row and one column.
The width of each column is the width of the widest cell in that column.
The height of each row is the height of the largest cell in that row.
For widgets that do not fill the entire cell, you can specify what happens to the extra
space. You can either leave the extra space outside the widget, or stretch the widget
to fit it, in either the horizontal or vertical dimension.
You can combine multiple cells into one larger area, a process called spanning.
Page 3
When you create a widget, it does not appear until you register it with a geometry
manager. Hence, construction and placing of a widget is a two-step process that goes
something like this:
w.grid ( *options )
This method registers a widget w with the Grid geometry managerif you dont do this,
the widget will exist but it will not be visible on the screen.
Here are the options to the .grid() geometry management method:
column
columnspan
ipadx
ipady
padx
pady
row
rowspan
sticky
Page 4
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 setting sticky to NE (top right),
SE (bottom right), SW (bottom left), or NW (top left).
You can position the widget against one side of the cell by setting sticky to N (top
center), E (right center), S (bottom center), or W (left center).
Set sticky to N+S to stretch the widget vertically but leave it centered horizontally.
Set sticky to E+W to stretch it horizontally but leave it centered vertically.
Set sticky=N+E+S+W to stretch the widget both horizontally and vertically to fill
the cell.
w.grid_forget()
This method makes widget w disappear from the screen. It still exists, it just isnt visible.
You can .grid() it to make it appear again, but it wont remember its grid options.
w.grid_propagate()
Normally, all widgets propagate their dimensions, meaning that they adjust to fit the
contents. However, sometimes you want to force a widget to be a certain size, regardless
of the size of its contents. To do this, call w .grid_propagate(0) where w is the widget
whose size you want to force.
w.grid_remove()
This method is like .grid_forget(), but its grid options are remembered, so if you
.grid() it again, it will use the same grid configuration options.
Page 5
3. Standard attributes
Before we look at the widgets, lets take a look at how some of their common attributes
such as sizes, colors and fontsare specified.
Each widget has a set of options that affect its appearance and behaviorattributes
such as fonts, colors, sizes, text labels, and such.
You can specify options when calling the widgets 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
widgets .config() method, and retrieve the current setting of any option by using
the widgets .cget() method. See Universal widget methods, below, for more on
these methods.
3.1 Dimensions
Various lengths, widths, and other dimensions of widgets can be described in various
units.
c
i
m
p
centimeters
inches
millimeters
1 00
printers points ( 72.27
)
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 Dimensions, above.
Page 6
3.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:
#rgb
#rrggbb
#rrrgggbbb
#rrrrggggbbbb
You can also use any locally defined standard color name. The strings "white",
"black", "red", "green", "blue", "cyan", "yellow", and "magenta" will also
be available. Others depending on your local installation.
3.4 Fonts
Depending on your platform, there may be up to three ways to specify type style.
As a tuple whose first element is the font family, followed by a size in points,
optionally followed by a string containing one or more of the style modifiers bold,
italic, underline, and overstrike.
Examples:
("Helvetica", "16")
("Times", "24", "bold italic")
You can create a font object by importing the tkFont module and using its Font
class constructor:
import tkFont
font = tkFont.Font ( *options )
where the options include:
family
size
weight
slant
underline
overstrike
If you are running under the X Window System, you can use any of the X font
names. For example, this font
"-*-lucidatypewriter-medium-r-*-*-*-140-*-*-*-*-*-*"
New Mexico Tech Computer Center
Page 7
is the authors favorite fixed-width font for use in X windows. 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 font objects:
.actual ( option=None )
If you pass no arguments, you get back a dictionary of the fonts 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 ( **options )
Use this method to change one or more options on a font. For example, if you have a
Font object called titleFont, if can 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 ( *options )
If you call this method with no arguments, it returns a dictionary of all the font metrics.
You can retrieve the value of just one metric by passing its name as an argument. Metrics
include:
ascent
descent
fixed
linespace
3.5 Bitmaps
For bitmap options in widgets, these bitmaps are guaranteed to be available:
The graphic above shows Button widgets with the standard bitmaps. From left to right,
they are "error", "gray75", "gray50", "gray25", "gray12", "hourglass", "info",
"questhead", "question", and "warning".
New Mexico Tech Computer Center
Page 8
3.6 Cursors
There are quite a number of different mouse cursors available. These are their names:
X_cursor
arrow
based_arrow_down
based_arrow_up
boat
bogosity
bottom_left_corner
bottom_right_corner
bottom_side
bottom_tee
box_spiral
center_ptr
circle
clock
coffee_mug
cross
cross_reverse
crosshair
diamond_cross
dot
dotbox
double_arrow
draft_large
draft_small
draped_box
exchange
fleur
gobbler
gumby
hand1
hand2
heart
icon
iron_cross
left_ptr
left_side
left_tee
leftbutton
ll_angle
lr_angle
man
middlebutton
mouse
pencil
pirate
plus
question_arrow
right_ptr
right_side
right_tee
rightbutton
rtl_logo
sailboat
sb_down_arrow
sb_h_double_arrow
sb_left_arrow
sb_right_arrow
sb_up_arrow
sb_v_double_arrow
shuttle
sizing
spider
spraycan
star
target
tcross
top_left_arrow
top_left_corner
top_right_corner
top_side
top_tee
trek
ul_angle
umbrella
ur_angle
watch
xterm
3.7 Images
To use graphic images in a Tkinter application, Tkinter must be configured to include the
Python Imaging Library (PIL).
Refer to the authors companion document, Python Imaging Library (PIL) quick reference,
for PIL documentation. Objects of the ImageTk class can be used in Tkinter applications.
Page 9
4. The
Button widget
The constructor returns the new button object. Its options include:
Background color when the button is under the
cursor.
activeforeground
Background color when the button is under the
cursor.
anchor
Where the text is positioned on the button: one
of CENTER (the default), N (centered along the top
edge), NE (top right corner), E, SE, S, SW, W, or NW.
bd
Border width in pixels. Also borderwidth.
bg
Normal background color. Also background.
bitmap
Name of one of the standard bitmaps to display on
the button (instead of text).
command
Function or method called when the button is
clicked.
cursor
Cursor used over the button.
default
NORMAL is the default; use DISABLED if the button
is to be initially disabled.
disabledforeground Foreground color used when the button is disabled.
fg
Normal foreground (text) color. Also foreground.
font
Text font.
height
Height of the button in text lines (for textual buttons) or pixels (for images).
highlightbackground Color of the focus highlight when the widget does
not have focus.
highlightcolor
Color shown in the focus highlight.
highlightthickness Thickness of the focus highlight.
image
Image to be displayed on the button (instead of
text).
justify
How to show multiple text lines: LEFT, CENTER (the
default), or RIGHT.
padx
Additional padding left and right of the text.
pady
Additional padding above and below the text.
relief
Default is RAISED, changing to SUNKEN when
pressed. May also be GROOVE, RIDGE, or FLAT.
state
Default is NORMAL. Set to DISABLED to gray out the
button and make it unresponsive. Has the value
ACTIVE when the mouse is over it.
takefocus
Normally, keyboard focus does visit buttons (see
the section on Focus, below, for an overview of keyboard focus), and a SPACE character acts as the same
as a mouse click, pushing the button. You can set
the takefocus option to zero to disable focus from
visiting the button.
text
Text displayed on the button. Use internal newlines
to display multiple text lines.
activebackground
Page 10
textvariable
underline
width
wraplength
.flash()
Causes the button to flash several times between active and normal colors. Leaves the
button in the state it was in originally. Ignored if the button is disabled.
.invoke()
Calls the buttons callback, and returns what that function returns. Has no effect if the
button is disabled or there is not callback.
5. The
Canvas widget
Creates a canvas in the given master window. See the following sections for the objects
that can be created on canvases:
.create_arc()
.create_bitmap()
.create_image()
.create_line()
.create_oval()
.create_polygon()
.create_rectangle()
.create_text()
.create_window()
Because the canvas may be larger than the window, and equipped with scrollbars to
move the overall canvas around in the window, there are two coordinate systems for
each canvas. The window coordinates of a point are relative to the top left corner of
the area on the display where the canvas appears. The canvas coordinates of a point
are relative to the top left corner of the total canvas.
bd
bg
closeenough
confine
New Mexico Tech Computer Center
Page 11
cursor
Cursor used in the canvas.
height
Size of the canvas in the Y dimension.
highlightbackground Color of the focus highlight when the widget does
highlightcolor
highlightthickness
relief
scrollregion
selectbackground
selectborderwidth
selectforeground
takefocus
width
xscrollincrement
xscrollcommand
yscrollincrement
yscrollcommand
The display list is an ordering of the objects on the canvas from back (background)
to front (foreground). If two objects overlap, the one above the other in the display
list means the one closer to the foreground, which will appear in the area of overlap
and obscure the one below. By default, new objects are always created at the top
of the display list (and hence in front of all other objects), but you can re-order the
display list.
The object ID of an object on the canvas is the value returned by the constructor for
that object.
A tag is a string that you can associate with any object or any number of objects on
the canvas.
Page 12
A tagOrId argument specifies one or more objects on the canvas. If a tag (string),
it specifies all the objects with that tag. If an Id (integer), it specifies the object that
has that ID number.
.addtag_all ( newTag )
Attaches the given tag newTag to all the objects on the canvas.
.bbox ( tagOrId=None )
Returns a tuple (x1 ; y1 ; x2 ; y2 ) describing a rectangle that encloses all the objects specified
by tagOrId. If the argument is omitted, returns a rectangle enclosing all objects on the
canvas. The top left corner of the rectangle is (x1 ; y1 ) and the bottom right corner is
(x2 ; y2 ).
Page 13
.delete ( tagOrId )
Deletes the specified object or objects.
tagOrId.
.find_above ( tagOrId )
Returns the ID number of the object just above the specified object. If multiple objects
match tagOrId, uses the highest one.
.find_all()
Returns a list of the ID numbers for all objects on the canvas, from lowest to highest.
.find_below ( tagOrId )
Returns the ID number of the object just below the specified object. If multiple objects
match tagOrId, uses the lowest one.
.find_withtag ( tagOrId )
Returns a list of the ID numbers of the object or objects specified by tagOrId.
Page 14
.focus ( tagOrId=None )
Moves the focus to the object specified by tagOrId. If there are multiple such objects,
moves the focus to the first one in the display list that allows an insertion cursor. If there
are no qualifying items, or the canvas does not have focus, focus does not move.
If the argument is omitted, returns the ID of the object that has focus, or "" if none of
them do.
.gettags ( tagOrId )
If tagOrId is an object ID, returns a list of all the tags associated with that object. If the
argument is a tag, returns all the tags for the lowest object that has that tag.
.postscript ( options )
Generates an Encapsulated PostScript representation of the canvass current contents.
The options include:
colormode
file
height
New Mexico Tech Computer Center
Page 15
rotate
x
y
width
.type ( tagOrId )
Returns the type of the first or only object specified by tagOrId. The return value
will be one of the strings "arc", "bitmap", "image", "line", "oval", "polygon",
"rectangle", "text", or "window".
.xview_moveto ( fraction )
This method scrolls the canvas in the same way as .xview(MOVETO, fraction).
New Mexico Tech Computer Center
Page 16
.xview_scroll ( n, what )
Same as .xview(SCROLL, n, what).
extent
fill
outline
outlinestipple
start
stipple
style
Page 17
width
id = C .create_bitmap ( x, y, *options )
which returns the integer ID number of the image object for that canvas.
Options include:
anchor
background
bitmap
foreground
tags
id = C .create_image ( x, y, *options )
This constructor returns the integer ID number of the image object for that canvas.
The image is positioned relative to point (x; y). See the anchor option, below, for
positioning options. Options include:
anchor
image
tags
New Mexico Tech Computer Center
Page 18
arrow
arrowshape
fill
smooth
splinesteps
stipple
tags
width
Page 19
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:
fill
outline
stipple
tags
width
fill
outline
Page 20
smooth
splinesteps
stipple
tags
width
The outline lies outside the canvas on its top and left sides, but inside the canvas on
its bottom and right side. The default appearance is a 1-pixel-wide black outline.
The fill is the area inside the outline. Its default appearance is transparent.
fill
outline
stipple
tags
width
Page 21
id = C .create_text ( x, y, *options )
This returns the unique integer ID of the text object on canvas C . Options include:
anchor
fill
font
justify
stipple
tags
text
width
The default is CENTER, meaning that the text is centered on the (x; y) position. Other possible values
are N, NE, E, SE, S, SW, W, and NW. For example, if
you specify anchor=W, the text will be positioned
so that point (x; y) is located at the center of the left
edge of the rectangle containing the text.
The default text color is black, but you can render it
in any color by setting the fill option to that color.
If you dont like the default font, set this option to
any font value. See the section on Fonts above.
For multi-line textual displays, this option controls
how the lines are justified: LEFT (the default), CENTER, or RIGHT.
If fill is set to a color, the default pattern is solid.
Set stipple to a bitmap (such as "gray20") to get
a stippled text pattern.
The tags to be associated with the object, as a sequence of strings.
The text to be displayed in the object, as a string.
Use newline characters ("\n") to force line breaks.
If you dont 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.
id = C .create_window ( x, y, *options )
This returns the unique integer ID for the window object. Options include:
anchor
height
Page 22
tags
width
window
The purpose of a checkbutton widget is to allow the user to read and set 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 thee IntVar class, so your
program can query and set the state of the checkbutton; see Control variables, below.
You can also use event bindings to react to user actions on the checkbutton; see
Events, below.
You can disable a checkbutton. This changes its appearance to grayed out and
makes it unresponsive to the mouse.
You can get rid of the checkbutton indicator and make the whole widget a pushpush button that looks recessed when it is set and raised when it is cleared.
activebackground
activeforeground
anchor
background
bitmap
borderwidth
New Mexico Tech Computer Center
Page 23
command
Page 24
selectimage
state
takefocus
text
textvariable
underline
variable
width
wraplength
.deselect()
Clears (turns off) the checkbutton.
.flash()
Flashes the checkbutton a few times between its active and normal colors, but leaves it
the way it started.
.invoke()
You can call this method to get the same actions that would occur if the user clicked on
the checkbutton to change its state.
.select()
Sets (turns on) the checkbutton.
.toggle()
Clears the checkbutton if set, sets it if cleared.
New Mexico Tech Computer Center
Page 25
If you want to display multiple lines of text that can be edited, see the Text widget,
below.
If you want to display a single line of text that cannot be modified, see the Label
widget, below.
For multiple-line displays that cant be modified, see the Message widget, below.
background
Page 26
textvariable
width
xscrollcommand
.get()
Returns the entrys current text as a string.
.icursor ( index )
Set the insertion cursor just before position index.
.index ( index )
Shift the contents of the entry so that the character at position index is the leftmost visible
character. Has no effect if the text fits entirely within the entry.
.insert ( index, s )
Inserts string s before the character at position index.
.xview ( index )
Same as .index().
.xview_moveto ( )
Positions the text in the entry so that the character at position , relative to the entire text,
is positioned at the left edge of the window. The argument must be in the range [0; 1],
where 0 means the left end of the text and 1 the right end.
entry.xview_scroll(-1, "pages")
entry.xview_scroll(4, "units")
New Mexico Tech Computer Center
Page 27
background
borderwidth
cursor
height
Page 28
takefocus
width
anchor
background
bitmap
borderwidth
cursor
Page 29
font
foreground
height
image
justify
padx
pady
relief
takefocus
text
textvariable
underline
width
wraplength
There are no special methods for label widgets other than the common ones (see Universal
widget methods, above).
Page 30
background
Page 31
takefocus
width
xscrollcommand
yscrollcommand
By default, the focus will tab through listbox widgets. Set this option to 0 to take the widget out of
the sequence. See Focus, below.
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.
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 below for more on
scrollable listbox widgets.
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 below for more on scrollable
listbox widgets.
A special set of index forms is used for many of the methods on listbox objects (below):
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 of the form "@x,y " refers to the line closest to coordinate (x; y ) relative to
the widgets upper left corner.
.activate ( index )
Selects the line specifies by the given index.
.curselection()
Returns a tuple containing the line numbers of the selected element or elements, counting
from 0. If nothing is selected, returns an empty tuple.
.index ( i )
If possible, positions the visible part of the listbox so that the line containing index i is at
the top of the widget.
Page 32
Insert one or more new lines into the listbox before the line specified by index. Use END
as the first argument if you want to add new lines to the end of the listbox.
.nearest ( y )
Return the index of the visible line closest to the y -coordinate y relative to the listbox
widget.
.see ( index )
Adjust the position of the listbox so that the line referred to by index is visible.
.selection_includes ( index )
Returns 1 if the line with the given index is selected, else returns 0.
.size()
Returns the number of lines in the listbox.
.xview()
To make the listbox horizontally scrollable, set the command option of the associated
horizontal scrollbar to this method. See Scrolling a Listbox widget, below.
.xview_moveto ( fraction )
Scroll the listbox so that the leftmost fraction of the width of its longest line is outside
the left side of the listbox. Fraction is in the range [0; 1].
.yview()
To make the listbox vertically scrollable, set the command option of the associated vertical
scrollbar to this method. See Scrolling a Listbox widget, below.
.yview_moveto ( fraction )
Scroll the listbox so that the top fraction of the width of its longest line is outside the
left side of the listbox. Fraction is in the range [0; 1].
Page 33
Refer to the section on the Menubutton widget, below, to see how to create a menubutton
and connect it to a Menu widget. First lets look at the Menu widget, which displays the
list of choices.
The choices displayed on a menu may be any of these things:
A simple command: a text string (or image) that the user can select to perform some
operation.
A cascade: a text string or image that the user can select to show another whole menu
of choices.
A checkbox.
A group of radiobuttons.
Page 34
To create a menu widget, you must first have created a Menubutton which we will call
mb:
activebackground
activeborderwidth
activeforeground
background
borderwidth
cursor
disabledforeground
font
foreground
postcommand
relief
selectcolor
tearoff
title
Page 35
These methods are available on Menu objects. The ones that create choices on the menu
have their own particular options, discussed below under coption.
.add_cascade ( *coption )
Add a new cascade element as the next available choice in self. Use the menu option in
this call to connect the cascade to the next levels 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
(described above).
.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.
.add_radiobutton ( *coption )
Add a new radiobutton as the next available choice in self. The options allow you to
set up the radiobutton much the same way as you would set up a Radiobutton object
(described below).
.add_separator()
Add a separator after the last currently defined option. This is just a ruled horizontal
line you can use to set off groups of choices. Separators are counted as choices, so if you
already have three choices, and you add a separator, the separator will occupy position
3 (counting from 0).
.index ( index )
Returns the position of the choice specified by index. For example, you can use .index(END) to find the index of the last choice (or None if there are no choices).
Page 36
.add_checkbutton().
.insert_command ( index, *coptions )
Insert a new command at position index. Options are the same as for .add_command().
.insert_separator ( index )
Insert a new separator at position index.
.invoke ( index )
Calls the command callback associated with the choice at position index. If a checkbutton,
its state is toggled; if a radiobutton, that choice is set.
.type ( index )
Returns the type of the choice specified by index: one of "cascade", "checkbutton",
"command", "radiobutton", "separator", or "tearoff".
These are the possible values of the coption choice options used in the methods above:
activebackground
activeforeground
background
bitmap
columnbreak
command
font
foreground
image
label
menu
offvalue
Page 37
onvalue
selectcolor
state
underline
value
variable
activebackground
activeforeground
anchor
background
bitmap
borderwidth
cursor
Page 38
direction
Page 39
width
wraplength
Here is a brief example showing the creation of a menubutton and its associated menu
with three checkboxes:
self.mb
self.mayoVar = IntVar()
self.ketchVar = IntVar()
self.mb.menu.add_checkbutton ( label="mayo",
variable=self.mayoVar )
self.mb.menu.add_checkbutton ( label="ketchup",
variable=self.ketchVar )
This example creates a menubutton labeled condiments. When clicked, two checkbuttons labeled mayo and ketchup will drop down.
The indicator is the diamond-shaped part that turns red in the selected item.
The label is the text, although you can use an image or bitmap as the label.
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 araised.
To form several radiobuttons into functional groups, create a single control variable
(see Control variables, 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.
Page 40
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 master:
activebackground
Page 41
indicatoron
justify
padx
pady
relief
selectcolor
selectimage
state
takefocus
text
textvariable
underline
value
Page 42
variable
width
wraplength
.deselect()
Clears (turns off) the radiobutton.
.flash()
Flashes the radiobutton a few times between its active and normal colors, but leaves it
the way it started.
.invoke()
You can call this method to get the same actions that would occur if the user clicked on
the radiobutton to change its state.
.select()
Sets (turns on) the radiobutton.
Each scale displays a slider that the user can drag along a trough to change the value. In
the figure, the first slider is currently at -0.38 and the second at 7.
You can drag the slider to a new value with mouse button 1.
If you click button 1 in the trough, the slider will move one increment in that
direction per click. Holding down button 1 in the trough will, after a delay, start to
auto-repeat its function.
Page 43
If the scale has keyboard focus, left arrow and up arrow keystrokes will move the
slider up (for vertical scales) or left (for horizontal scales). Right arrow and down
arrow keystrokes will move the slider down or to the right.
To create a new scale widget as the child of a root window or frame named master:
activebackground
background
Page 44
relief
repeatdelay
repeatinterval
resolution
showvalue
sliderlength
state
takefocus
tickinterval
to
troughcolor
Page 45
variable
width
The control variable for this scale, if any. See Control variables, below. Control variables may be from
class IntVar, DoubleVar (float), or StringVar. In
the latter case, the numerical value will be converted to a string. See the digits option, above,
for more information on this conversion.
The width of the trough part of the widget. This is
the x dimension for vertical scales and the y dimension if the scale has horizontal orientation. Default
is 15 pixels.
.get()
This method returns the current value of the scale.
.set(value)
Sets the scales value.
The slider, or scroll thumb, is the raised-looking rectangle that shows the current
scroll position.
The two triangular arrowheads at each end are used for moving the position by small
steps.
The trough is the sunken-looking area visible behind the arrowheads and slider.
Scrollbars can be horizontal, like the one shown above, or vertical. A widget that has
two scrollable dimensions, like a canvas, can have both a horizontal and a vertical
scrollbar.
The sliders 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
Page 46
to the discussion of the associated widget to find out the exact amount that these
actions move the view.
The user can drag the slider with B1 or B2 (the middle button) to move the view.
For a horizontal scrollbar, clicking B1 in the trough to the left of the slider moves the
view left by a page, and clicking B1 in the trough to the right of the slider moves the
view a page to the right. For a vertical scrollbar, the corresponding actions move
the view a page up or down.
Clicking B2 anywhere along the trough moves the slider so that its left or top end is
at the mouse, or as close to it as possible.
To create a new scrollbar widget as the child of a root window or frame master:
activebackground
Page 47
repeatinterval
takefocus
troughcolor
width
When the user requests a movement of one unit left or up, for example by clicking
button B1 on the left or top arrowhead, the arguments to the callback look like:
When the user requests a movement of one unit right or down, the arguments are:
command("scroll", 1, "units")
command("scroll", 1, "pages")
When the user drags the slider to a value of 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", )
These calling sequences match the arguments expected by the .xview() and .yview()
methods of canvases, listboxes, and text widgets. However, for some reason, the entry
widget does not have an .xview() method. See the section Scrolling an Entry widget,
above.
Page 48
=
=
self.scrollX.set
self.scrollY.set
Notes:
The connection goes both ways. The canvass xscrollcommand option has to be
connected to the horizontal scrollbars .set method, and the scrollbars command
option has to be connected to the canvass .xview method. The vertical scrollbar
and canvas must have the same mutual connection.
The sticky options on the .grid() method calls for the scrollbars force them to
stretch just enough to fit the corresponding dimension of the canvas.
To use a text widget, there are two other concepts you will need to understand:
Refer to the separate sections below for more on the theory and practice of indices, marks,
images, windows, and tags.
New Mexico Tech Computer Center
Page 49
line.end
INSERT
CURRENT
END
SEL_FIRST
SEL_LAST
markname
tag.first
tag.last
"@x,y "
embedded-object
You handle each mark by giving it a name. This name can be any string that doesnt
include whitespace or periods.
There are two special marks. INSERT is the current position of the insertion cursor,
and CURRENT is the position closest to the mouse cursor.
Marks floating along with the adjacent content. If you modify text somewhere away
from a mark, the mark stays at the same position relative to its immediate neighbors.
Marks have a property called gravity that controls what happens when you insert
text at a mark. The default gravity is RIGHT, which means that when new text is
inserted at that mark, the mark stays after the end of the new text. If you set the
gravity of a mark to LEFT (using the text widgets .mark_gravity() method), the
mark will stay at a position just before text newly inserted at that mark.
Deleting the text all around a mark does not remove the mark. If you want to remove
a mark, use the .mark_unset() method on the text widget.
Page 50
The name of a tag can be any string that does not contain white space or periods.
There is one special predefined tag called SEL. This is the region currently selected,
if any.
Since any character may be part of more than one tag, there is a tag stack that orders
all the tags. Entries are added at the end of the tag list, and later entries have priority
over earlier entries. So, for example, if there is a character c that is part of two tagged
regions t1 and t2 , and t1 is deeper in the tag stack than t2 , and t1 wants the text to be
green and t2 wants it to be blue, c will be rendered in blue because t2 has precedence
over t1 .
You can change the ordering of tags in the tag stack.
Tags are created by using the .tag_add() method on the text widget. See Methods on
text widgets, below, for information on this and related methods.
Page 51
background
Page 52
selectforeground
spacing1
spacing2
spacing3
state
tabs
takefocus
width
Page 53
wrap
xscrollcommand
yscrollcommand
.image_names()
This method returns a tuple of the names of all the text widgets embedded images.
.index ( i )
For an index i, this method returns the equivalent position in the form "line.char".
Page 54
.mark_names()
Returns a sequence of the names of all the marks in the window, including INSERT and
CURRENT.
.mark_set ( mark, index )
If no mark with name mark exists, one is created with RIGHT gravity and placed where
index points. If the mark already exists, it is moved to the new location.
.mark_unset ( mark )
Removes the named mark.
backwards
count
regexp
(: : : ) * + ? e1 |e2
nocase
stopindex
.see ( index )
If the text containing the given index is not visible, scroll the text until it is.
Page 55
background
bgstipple
borderwidth
fgstipple
font
foreground
justify
lmargin1
Page 56
lmargin2
offset
overstrike
relief
rmargin
spacing1
spacing2
spacing3
tabs
underline
wrap
.tag_delete ( *tagName )
To delete one or more tags, pass their names to this method. Their options and bindings
go away, and the tags are removed from all regions of text.
.tag_names ( index=None )
If you pass an index argument, this method returns a sequence of all the tag names that
are associated with the character after that index. If you pass no argument, you get a
sequence of all the tag names defined in the text widget.
Page 57
If there is a place in the given region where that tag starts, the method returns a sequence
[i0 , i1 ], where i0 is the index of the first tagged character and i1 is the index of the
position just after the last tagged character.
If no tag starts are found in the region, the method returns an empty string.
.tag_ranges ( tagName )
This method finds all the ranges of text in the widget that are tagged with name tagName,
and returns a sequence [s0 , e0 , s1 , e1 , : : : ], where each si is the index just before the
first character of the range and ei is the index just after the last character of the range.
you can use pass the widget to the window option in this method, or
you can define a procedure that will create the widget and pass that procedure as a
callback to the create option.
Page 58
align
create
padx
pady
stretch
window
.window_names()
Returns a sequence containing the names of all embedded widgets.
.xview_moveto ( fraction )
This method scrolls the text in the same way as .xview(MOVETO, fraction).
.xview_scroll ( n, what )
Same as .xview(SCROLL, n, what).
.yview(MOVETO, fraction)
.yview(SCROLL, n, what)
.yview_moveto(fraction)
.yview_scroll(n, what)
These are the same as the .xview() and related methods, only for vertical scrolling.
When scrolling verticallly by UNITS, the units are lines.
Page 59
17.
Toplevel ( options )
Options include:
background
borderwidth
class_
*Screamer*background: red
and then, if you use the .option_readfile()
cursor
height
relief
width
.deiconify()
If iconified, expand.
.geometry ( newGeometry=None )
Set the window geometry. The argument has the form "w xh x y "; if omitted, the
current geometry string is returned.
.iconify()
Iconify the window.
.lift ( aboveThis=None )
To raise this window to the top of the stacking order in the window manager, call this
method with no arguments. You can also raise it to a position in the stacking order just
above another Toplevel window by passing that window as an argument.
Page 60
.lower ( belowThis=None )
If the argument is omitted, moves the window to the bottom of the stacking order in the
window manager. You can also move the window to a position just under some other
top-level window by passing that Toplevel widget as an argument.
.title ( string=None )
Set the window title. If the argument is omitted, returns the current title.
.withdraw()
Hide the window. Restore it with .deiconify() or .iconify().
w.after_cancel ( id )
Cancels a request for callback set up earlier .after(). The id argument is the result
returned by the original .after() call.
w.bell()
Makes a noise, usually a beep.
Page 61
w.bindtags ( tagList=None )
If you call this method, it will return the binding tags for the widget as a sequence of
strings. A binding tag is the name of a window (starting with ".") or the name of a class
(e.g., "Listbox").
You can change the order in which binding levels are called by passing as an argument
the sequence of binding tags you want the widget to use.
See Events, below, for a discussion of binding levels and their relationship to tags.
w.cget ( option )
Returns the current value of option as a string. You can also get the value of an option
for widget w as w [option].
w.clipboard_append ( string )
Appends the given string to the displays clipboard, where cut and pasted strings are
stored for all that displays applications.
w.clipboard_clear()
Clears the displays clipboard (see .clipboard_append(), above).
Set the values of one or more options. For the options whose names are Python reserved
words (class, tt from, in), use a trailing underbar: class_, tt from_, in_).
You can also set the value of an option for widget w with the statement
w[option] = value
If you call the .config() method on a widget with no arguments, youll get a dictionary
of all the widgets 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).
You can use either .config() or .configure(); the two names are equivalent.
New Mexico Tech Computer Center
Page 62
w.destroy()
Calling w .destroy() on a widget w destroys w and all its children.
w.event_info ( virtual=None )
If you call this method without an argument, youll get back a sequence of all the currently
defined virtual event names.
To retrieve the physical events associated with a virtual event, pass this method the name
of the virtual event and you will get back a sequence of the physical sequence names,
or None if the given virtual event has never been defined.
w.focus_displayof()
Returns the name of the window that currently has input focus on the same display as
the widget. If no such window has input focus, returns None.
See Focus, below, for a general description of input focus.
w.focus_force()
Force the input focus to the widget. This is impolite. Better to wait for the window
manager to give you the focus.
w.focus_get()
Get the name of the widget that has focus in this application, if anyotherwise return
None.
w.focus_lastfor()
This method retrieves the name of the widget that last had the input focus in the top-level
window that contains w . If none of this top-levels widgets have ever had input focus,
it returns the name of the top-level widget. If this application doesnt have the input
focus, the .focus_lastfor() method will return the name of the widget that will get
the focus next time it comes back to this application.
New Mexico Tech Computer Center
Page 63
w.focus_set()
If w s application has the input focus, the focus will jump to w . If w s application doesnt
have focus, Tk will remember to give it to w next the application gets focus.
w.grab_current()
If there is a grab in force for w s display, return its identifier, otherwise return None. Refer
to Events, below, for a discussion of grabs.
w.grab_release()
If w has a grab in force, release it.
w.grab_set()
Widget w grabs all events for w s application. If there was another grab in force, it goes
away. See Events, below, for a discussion of grabs.
w.grab_set_global()
Widget w grabs all events for the entire screen. This is considered impolite and should
be used only in great need. Any other grab in force goes away.
w.grab_status()
If there is a local grab in force (set by .grab_set()), this method returns the string
"local". If there is a global grab in force (from .grab_set_global()), it returns
"global". If no grab is in force, it returns None.
w.image_names()
Returns the names of all the images in w s application as a sequence of strings.
w.keys()
Returns the option names for the widget as a sequence of strings.
w.mainloop()
This method must be called, generally after all the static widgets are created, to start
processing events. You can leave the main loop with the .quit() method (below). You
can also call this method inside an event handler to resume the main loop.
w.nametowidget ( name )
This method returns the actual widget whose path name is name. The path name for any
widget x is str(x); see also the .winfo_pathname() method, below.
widgetDefault
startupFile
userDefault
interactive
New Mexico Tech Computer Center
Page 64
*Button*font:
times 24 bold
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.quit()
This method exits the main loop. See .mainloop(), above, for a discussion of main
loops.
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.
Page 65
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 the section on Focus, below. 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.unbind_all ( sequence )
Deletes all event bindings throughout the application for the event described by the given
sequence.
w.update()
This method forces the updating of the display. It should be used only if you know what
youre doing, since it can lead to unpredictable behavior or looping. It should never be
called from an event callback or a function that is called from an event callback.
w.update_idletasks()
Some tasks in updating the display, such as resizing and redrawing widgets, are called
idle tasks because they are usually deferred until the application has finished handling
events and has gone back to the main loop to wait for new events.
If you want to force the display to be updated before the application next idles, call the
w.update_idletasks() method on any widget.
w.winfo_children()
Returns a list of all w s children, in their stacking order from lowest (bottom) to highest
(top).
w.winfo_class()
Returns w s class name (e.g., "Button").
w.winfo_colormapfull()
Returns true if w s windows color map is full, that is, if the last attempt to add a color to
it failed and no colors have been removed since then.
New Mexico Tech Computer Center
Page 66
w.winfo_depth()
Returns the number of bits per pixel in w s display.
w.winfo_fpixels ( number )
For any dimension number (see Dimensions, above), this method returns that distance in
pixels on w s display, as a floating-point number.
w.winfo_geometry()
Returns the geometry string describing the size and on-screen location of w as a string
"wxh+x+y ", where w is the width, h is the height, and the upper left corner of the widget
is at (x, y ) relative to the upper left corner of its top-level window. Warning: the geometry
is not accurate until the application has updated its idle tasks. In particular, all geometries
are initially "1x1+0+0" until the widgets and geometry manager have negotiated their
sizes and positions. See the .update_idletasks() method, above, in this section to see
how to insure that the widgets geometry is up to date.
w.winfo_height()
Returns the current height of w in pixels. See the remarks on geometry updating under
.winfo_geometry(), above.
w.winfo_id()
Returns an integer that uniquely identifies w within its top-level window. You will need
this for the .winfo_pathname() method, below.
w.winfo_ismapped()
This method returns true if w is mapped, false otherwise. A widget is mapped if it has
been gridded (or placed or packed, if you are using one of the other geometry managers)
into its parent, and if its parent is mapped, and so on up to the top-level window.
w.winfo_manager()
If w has not been gridded (or placed via one of the other
geometry managers), this method returns an empty string. If w has been gridded or
otherwise placed, it returns a string naming the geometry manager, such as "grid".
w.winfo_name()
This method returns w s name relative to its parent. Widget names have a hierarchical
path name structure somewhat like path names in a file system. A widget that is the
child of a top-level window has a name of the form ".n", where n is the widgets name
as returned by .winfo_name(). Any other widget has a name of the form pp .n, where
pp is the path name of its parent and n is its own name. See .winfo_pathname(), below,
to find out how to obtain a widgets path name.
w.winfo_parent()
Returns w s parents path name, or an empty string if w is a top-level window. See
.winfo_name(), above, for more on widget path names.
New Mexico Tech Computer Center
Page 67
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()
w.winfo_pointery()
w.winfo_pointerxy()
The first two methods return the x and y coordinates, respectively, of the mouse pointer
relative to w s root window. If the mouse pointer isnt on the same screen, each will
return -1. The third method returns a tuple (x, y ), or (-1, -1).
w.winfo_reqheight()
w.winfo_reqwidth()
These methods return the requested height and width, respectively, of widget w . These
dimensions are the ones necessary so that all of w s contents have the room they need.
The actual height and width may be different due to negotiations with the geometry
manager.
w.winfo_rgb ( color )
For any given color (see Colors, above, for the various ways of specifying colors), this
method returns the equivalent red-green-blue color specification as a 3-tuple (r , g , b),
where each number is an integer in the range [0; 65536]. For example, if the color is
"green", this method returns the 3-tuple (0, 65535, 0).
w.winfo_rootx()
w.winfo_rooty()
Returns the x and y coordinates, respectively, of the upper left-hand corner of w s root
window relative to w s parent. If w has a border, this is the outer corner of the border.
w.winfo_screenheight()
w.winfo_screenwidth()
w.winfo_screenmmheigh()
w.winfo_screenmmwidth()
These methods retrieve the size of the screen. The first two return the height and width,
respectively, in pixels. The latter two return the screen size in millimeters, as an integer.
w.winfo_screenvisual()
Returns a string that describes the displays method of color rendition. This is usually
"truecolor" for 16- or 24-bit displays, "pseudocolor" for 256-color displays.
w.winfo_toplevel()
Returns the top-level window containing w . That window supports all the methods on
Toplevel widgets; see the section on Toplevel, above.
New Mexico Tech Computer Center
Page 68
w.winfo_x()
w.winfo_y()
These methods return the x and y coordinates, respectively, of the top left corner of w
relative to its parent. If w has a border, this is the outer corner of the border.
if you want a lot of widgets to have the same background color or font, its tedious
to specify each option each time, and
its nice to let the user override your choices with their favorite color schemes, fonts,
and other choices.
Accordingly, we use the idea of an option database to set up default option values.
Your application can specify a file (such as the standard .Xdefaults file used by
the X Window System) that contains the users preferences. You can set up your
application to read the file and tell Tkinter to use those defaults. See the on the
.option_readfile() method, above, in the section on Universal widget methods.
See the section on Resource specification lines, below, for the structure of this file.
Your application can directly specify defaults for one or many types of widgets by
using the .option_add() method; see this method in the section Universal widget
methods, above.
Before we discuss how options are set, consider the problem of customizing the appearance of GUIs in general. We could give every widget in the application a name, and
then ask the user to specify every property of every name. But this is cumbersome, and
would also make the application hard to reconfigureif the designer adds new widgets,
the user would have to describe every property of every new widget.
So, the option database allows the programmer and the user to specify general patterns
describing which widgets to configure.
These patterns operate on the names of the widgets, but widgets are named using two
parallel naming schemes:
Every widget has a class name. By default, the class name is the same as the class
constructor: "Button" for buttons, "Frame" for a frame, and so on. However, you
can create new classes of widgets, usually inheriting from the Frame class, and give
them new names of your own creation. See the section How to name a widget class,
below, for details.
You can also give any widget an instance name. The default name of a widget is
usually a meaningless number (e.g., "135147872" is a value that might come up in
the X implementation). However, as with widget classes, you can assign a name to
any widget. See the section How to name a widget instance, below, for details.
Every widget in every application therefore has two hierarchies of namesthe class name
hierarchy and the instance name hierarchy. For example, a button embedded in a text
widget which is itself embedded in a frame would have the class hierarchy
New Mexico Tech Computer Center
Page 69
Frame.Text.Button
It might also have an instance hierarchy something like
.mainFrame.messageText.panicButton
if you so named all the instances. The initial dot stands for the root window; see the
.winfo_pathname() method in the section on universal widget methods, above, for
more information on pathnames.
The option database mechanism can make use of either class names or instance names in
defining options, so you can make options apply to whole classes (e.g., all buttons have
a blue background) or to specific instances (e.g., the panic button has red letters on it).
After we look at how to name classes and instances, in the section on Resource specification
lines, below, well discuss how the options database really works.
class Jukebox(Frame):
def __init__(self, master):
"""Constructor for the Jukebox class"""
Frame.__init__ ( self, master, class_="Jukebox" )
self.__createWidgets()
...
19.2 How to name a widget instance
To give an instance name to a specific widget in your application, set that widgets name
option to a string containing the name.
Heres an example of an instance name. Suppose you are creating several buttons in an
application, and you want one of the buttons to have an instance name of panicButton.
Your call to the constructor might look like this:
xparrot*background:
New Mexico Tech Computer Center
LimeGreen
Page 70
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:
The way the option patterns work is a little complicated. Lets start with a simple
example:
*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 well talk about how Tkinter figures out exactly which option value to
use if there are multiple resource specification lines that apply.
Page 71
*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:
Page 72
Checkbuttons use a control variable to hold the current state of the checkbutton (on
or off).
A single control variable is shared by a group of radiobuttons and can be used to
tell which one of them is currently set. When the user clicks on one radiobutton in a
group, the sharing of this control variable is the mechanism by which Tkinter groups
radiobuttons so that when you set one, any other set radiobutton in the group is
cleared.
Control variables hold text string for several applications. Normally the text displayed in an Entry widgets is linked to a control variable. In several other controls,
it is possible to use a string-valued control variable to hold text such as the labels of
checkbuttons and radiobuttons and the content of Label widgets.
For example, you could link an Entry widget to a Label widget so that when the
user changes the text in the entry and presses the Enter key, the label is automatically
updated to show that same text.
To get a control variable, use one of these four class constructors, depending on what
type of values you want to store in it:
v = DoubleVar()
v = IntVar()
v = StringVar()
.get()
Returns the current value of the variable.
.set ( value )
Changes the current value of the variable. If any widget options are slaved to this variable,
those widgets will be updated when the main loop next idles; see .update_idletasks()
New Mexico Tech Computer Center
Page 73
in the section on Universal widget methods, above, for more information on controlling this
update cycle.
Here are some comments on how control variables are used with specific widgets:
Button: You can set its textvariable to a StringVar. Anytime that variable is
changed, the text on the button will be updated to display the new value. This is not
necessary unless the buttons text is actually going to change: use the text attribute
if the buttons label is static.
Checkbutton: Normally, you will set the widgets variable option to an IntVar,
and that variable will be set to 1 when the checkbutton is turned on and to 0 when
it is turned off. However, you can pick different values for those two states with the
onvalue and offvalue options, respectively. You can even use a StringVar as the
checkbuttons variable, and supply string values for the offvalue and onvalue.
Heres an example:
self.spamVar = StringVar()
self.spamCB = Checkbutton ( self, text="Spam?",
variable=self.spamVar, onvalue="yes", offvalue="no" )
If this checkbutton is on, self.spamVar.get() will return the string "yes"; if the
checkbutton is off, that same call will return the string "no". Furthermore, your
program can turn the checkbutton on by calling .set("yes").
You can also the textvariable option of a checkbutton to a StringVar. Then
you can change the text label on that checkbutton using the .set() method on that
variable.
Entry: Set its textvariable option to a StringVar. Use that variables .get()
method to retrieve the text currently displayed in the widget. You can also the
variables .set() method to change the text displayed in the widget.
Label: You can set its textvariable option to a StringVar. Then any call to
the variables .set() method will change the text displayed on the label. This is
not necessary if the labels text is static; use the text attribute for labels that dont
change while the application is running.
Menubutton: If you want to be able to change the text displayed on the menu
button, set its textvariable option to a StringVar() and use that variables
.set() method to change the displayed text.
Radiobutton: The variable option must be set to a control variable, either an
IntVar or a StringVar. All the radiobuttons in a functional group must share the
same control variable. Set the value option of each radiobutton in the group to a
different value. Whenever the user sets a radiobutton, the variable will be set to
the value option of that radiobutton, and all the other radiobuttons that share the
group will be cleared.
You might wonder, what state is a group of radiobuttons in when the control variable
has never been set and the user has never clicked on them? Each control variable
has a default value: 0 for an IntVar, 0.0 for a DoubleVar, and "" for a StringVar.
If one of the radiobuttons has that value, that radiobutton will be set initially. If no
radiobuttons value option matches the value of the variable, the radiobuttons will
all appear to be cleared.
Page 74
If you want to change the text label on a radiobutton during the execution of your
application, set its textvariable option to a StringVar. Then your program can
change the text label by passing the new label text to the variables .set() method.
Scale: For a scale widget, set its variable option to a control variable of any class,
and set its from_ and to options to the limiting values for the opposite ends of
the scale. For example, you could use an IntVar and set the scales from_=0 and
to=100. Then every user change to the widget would change the variables value to
some value between 0 and 100 inclusive. Your program can also move the slider by
using the .set() method on the control variable. To continue the above example,
.set(75) would move the slider to a position three-fourths of the way along its
trough.
To set up a Scale widget for floating values, use a DoubleVar.
You can use a StringVar as the control variable of a Scale widget. You will still
need to provide numeric from_ and to values, but the numeric value of the widget
will be converted to a string for storage in the StringVar. Use the scales digits
option to control the precision of this conversion.
By focus traversal, we mean the sequence of widgets that will be visited as the user
moves from widget to widget with the TAB key. See below for the rules for this
sequence.
You can traverse backwards using SHIFT-TAB.
The Entry and Text widgets are intended to accept keyboard input, and if an entry
or text widget currently has the focus, any characters you type into it will be added
to its text.
Because Text widgets can contain tab characters, you must use the special key
sequence CONTROL-TAB to move the focus past a text widget.
Most of the other types of widgets will normally be visited by focus traversal, and
when they have focus:
Page 75
Many widgets are provided with an outline called the focus highlight that shows the
user which widget has the highlight. This is normally a thin black frame located
just outside the widgets border (if any). For widgets that dont normally have a
focus highlight (specifically, frames, labels, and menus), you can set its highlightthickness option to a nonzero value to make the focus highlight visible.
You can also change the color of the focus highlight using the highlightcolor
option.
Widgets of class Frame, Label, and Menu are not normally visited by the focus.
However, you can set their takefocus options to 1 to get them included in focus traversal. You can also take any widget out of focus traversal by setting its
takefocus option to 0.
The order in which the TAB key traverses the widgets is:
For widgets that are children of the same parent, focus goes in the same order the
widgets were created.
For parent widgets that contain other widgets (such as frames), focus visits the
parent widget first (unless its takefocus option is 0), then it visits the child widgets,
recursively, in the order they were created.
To sum up: to set up the focus traversal order of your widgets, create them in that order.
Remove widgets from the traversal order by setting their takefocus options to 0, and
for those whose default takefocus option is 0, set it to 1 if you want to add them to the
order.
The above describes the default functioning of input focus in Tkinter. There is another,
completely different way to handle itlet the focus go wherever the mouse goes. Under
Universal widget methods, above, refer to the .tk_focusFollowsMouse() method.
You can also add, change or delete the way any key on the keyboard functions inside any
widget by using event bindings. See Events, below, for the details.
Page 76
Page 77
<[modifier-]...type[-detail]>
The usual setup has button 1 on the left and button 3 on the right, but lefthanders can swap these positions.
For keys on the keyboard, this is either the keys character (for single-character
keys like the A or * key) or the keys name; see below for a list of all key names.
Here are some examples to give you the flavor of event patterns:
Activate
Button
ButtonRelease
Configure
Deactivate
Destroy
Page 78
Enter
Expose
FocusIn
FocusOut
KeyPress
KeyRelease
Leave
Map
Motion
Unmap
Visibility
Alt
Any
Control
Double
Lock
Shift
Triple
You can use shorter forms of the events. Here are some examples:
Page 79
Note that you can leave out the enclosing <: : : > for most single-character keypresses, but
you cant do that for the space character (whose name is <space>) or the less-than (<)
character (whose name is <less>).
The .keysym column shows the key symbol, a string name for the key. This
corresponds to the .keysym member of the Event object.
The .keycode column is the key code. This identifies which key was pressed,
but the code does not reflect the state of various modifiers like the shift and control
keys and the NUMLOCK key. So, for example, both a and A have the same key code.
The .keysym_num column shows a numeric code equivalent to the key symbol.
Unlike .keycode, these codes are different for different modifiers. For example,
the digit 2 on the numeric keypad (key symbol KP_2) and the down arrow on the
numeric keypad (key symbol KP_Down) have the same key code (88), but different
.keysym_num values (65433 and 65458, respectively).
The Key column shows the text you will usually find on the physical key, such as
TAB.
There are many more key names for international character sets. This table shows only
the Latin-1 set for the usual USA-type 101-key keyboard.
Page 80
Linefeed
KP_0
KP_1
KP_i
:::
KP_9
KP_Add
KP_Begin
54
90
91
90+i
81
86
84
106
65456
65457
65456+i
Linefeed (CONTROL-J)
0 on the keypad
1 on the keypad
Digit i on the keypad
KP_Decimal
KP_Delete
KP_Divide
KP_Down
KP_End
KP_Enter
KP_Home
KP_Insert
KP_Left
KP_Multiply
KP_Next
KP_Prior
KP_Right
KP_Subtract
KP_Up
Next
Num_Lock
Pause
Print
Prior
Return
91
91
112
88
87
108
79
90
83
63
89
81
85
82
80
105
77
110
111
99
36
65454
65439
65455
65433
65436
65421
65429
65438
65430
65450
65435
65434
65432
65453
65431
65366
65407
65299
65377
65365
65293
. on the keypad
DELETE
on the keypad
/ on the keypad
# on the keypad
on the keypad
ENTER on the keypad
HOME on the keypad
INSERT on the keypad
on the keypad
on the keypad
PAGEDOWN on the keypad
PAGEUP on the keypad
! on the keypad
on the keypad
" on the keypad
PAGEDOWN
NUMLOCK
END
PAUSE
PRINTSCRN
PAGEUP
The ENTER key (CONTROL-M).
The name
Right
Scroll_Lock
Shift_L
Shift_R
Tab
Up
102
78
50
62
23
98
65363
65300
65505
65506
65289
65362
SCROLLLOCK
The left-hand SHIFT key
The right-hand SHIFT key
The TAB key
"
Page 81
.char
.height
.keysym
.keysym_num
.num
.time
.widget
.width
.x
.y
.x_root
.y_root
Heres an example of an event handler. Under Levels of binding, 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:
New Mexico Tech Computer Center
Page 82
need. Line 5 above builds a nameless function that takes three arguments. The first
argument will have a default value of self. The second argument will receive the Event
object that always gets passed to event handlers. And the third argument defaults to the
value of i, which is the current checkbutton number.
So, although Tkinter will pass only two arguments to this handler, the third value is
supplied from the default third argument value, the checkbutton number, i.
This technique can be extended to supply any number of additional arguments to handlers.
New Mexico Tech Computer Center
Page 83
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 Universal widget
methods, above, for more information about creating and managing virtual events.
Page 84