Table of Contents
Tkinter is an open source, portable graphical
user interface (GUI) library designed for use in Python scripts.
Tkinter relies on the Tk library, the GUI library used by Tcl/Tk
and Perl, which is in turn implemented in C. Therefore, Tkinter
can be said to be implemented using multiple layers.
Several competing GUI toolkits are available to use with the
Python language, namely:
The layered approach used in designing Tkinter gives Tkinter all of the advantages of the TK library. Therefore, at the time of creation, Tkinter inherited from the benefits of a GUI toolkit that had been given time to mature. This makes early versions of Tkinter a lot more stable and reliable than if it had been rewritten from scratch. Moreover, the conversion from Tcl/Tk to Tkinter is really trivial, so that Tk programmers can learn to use Tkinter very easily.
Learning Tkinter is very intuitive, and therefore quick and painless. The Tkinter implementation hides the detailed and complicated calls in simple, intuitive methods. This is a continuation of the Python way of thinking, since the language excels at quickly building prototypes. It is therefore expected that its preferred GUI library be implemented using the same approach. For example, here is the code for a typical Hello world-like application:
from Tkinter import *
root = Tk( )
root.title("A simple application")
root.mainloop( )
The first 2 lines allow to create a complete window. Compared to MFC programming, it makes no doubt that Tkinter is simple to use. The third line sets the caption of the window, and the fourth one makes it enter its event loop.
Python scripts that use Tkinter do not require modifications to be ported from one platform to the other. Tkinter is available for any platform that Python is implemented for, namely Microsoft Windows, X Windows, and Macintosh. This gives it a great advantage over most competing libraries, which are often restricted to one or two platforms. Moreover, Tkinter will provide the native look-and-feel of the specific platform it runs on.
Tkinter is now included in any Python distribution. Therefore, no supplementary modules are required in order to run scripts using Tkinter.
The multi-layered approach taken in designing Tkinter can have some disadvantages as far as execution speed is concerned. While this could constitute a problem with older, slower machines, most modern computers are fast enough so as to cope with the extra processing in a reasonable time. When speed is critical, proper care must be taken so as to write code that is as efficient as possible.
Tkinter widgets are a subset of classes in Tkinter. They all inherit
from the class Widget. Each one of them, when instantiated, creates
a window component that can be styled to respond to the programmers
need. To control the appearance of a widget, you usually use options
rather than method calls. Typical options include text and color,
size, command callbacks, etc. (see table below) When widgets are
instantiated, they dont immediately appear on the screen.
Geometric managers (pack, grid, place) have to be called in order to
make the widget visible on the screen. These last are also classes
which inherit from the widget class. Aside from the methods
inherited from the parent class Widget, each one of them has distinct
options and methods suitable for configuration of the particular
widget. Therefore, Tkinter widgets dont only provide a tool to
build a graphical interface, it also allows the programmers to create
a fully functional application.
Note that there is no class hierarchy between widgets classes.
All widget are siblings in the hierarchy tree.
Option | Value | Effect |
---|---|---|
foreground (fg) | Colour | Changes the foreground colour. (Colour may be specified using pre-defined keywords or using RGB values) |
background (bg) | Colour | Changes the background colour. (Colour may be specified using pre-defined keywords or using RGB values) |
bd (border width) | integer | Specifies the width of the widget border |
command | Callbacktype | Specifies which method is to be executed when the widget is selected. |
font | Font type | Specifies the font used by the widget. Often represented in a tuple (family, size, weight) |
padx, pady | Integer | Specifies the width between the current widget and the neighbor widgets. |
relief |
Relief type:
|
Specifies the relief of the widget. |
text | string | Specifies the text appearing on the widget at run time |
To configure any widgets options, all widget implements the same configuration interface:
Interface method | Return Value | Effect |
---|---|---|
widgetclass(master, option = value, ...) | String | Creates an instance of this widget using the given options. (Options may be modified later). |
cget(option) | String | Returns the current value of the specified option. |
configure(option = value, ...) | none | Configures option(s) for the widget. |
keys( ) | list | Returns a list of all options that can be set for this widget. |
There are 14 core widgets that Tkinter provides.
Description |
This widget works pretty much like Frames, except it is displayed in a separate, top-level window. Toplevel usually have title bars, borders and other windows decorations |
|
---|---|---|
Options | width, height | Specifies the size of toplevel window |
cursor | Specifies the cursor to show when the cursor is within the toplevel window | |
menu | A menu to be associated with this window | |
Methods | None except from standard Tkinter method |
Description | A Frame is rectangular region on the screen. The frame widget is mainly used as a geometry master for other widgets, or to provide padding between other widgets. | |
---|---|---|
Options | width, height | Specifiesthe size of toplevel window. |
cursor | Specifies the cursor to show when the cursor is within the frame. | |
takefocus | Indicates that the user can use the Tab key to move to this widget. | |
Methods | None except from standard Tkinter method |
Description |
The Label widget is a standard Tkinter widget used to display a text or image on the screen. The button can only display text in a single font, but the text may span more than one line. In addition, one of the characters can be underlined, for example to mark a keyboard shortcut. |
|
---|---|---|
Options | text | The text to be displayed by the label. |
textvariable |
Associates a Tkinter variable (usually a StringVar) to the label. If the variable is changed, the label text is updated. |
|
justify |
Defines how to align multiple lines of text. Use LEFT, RIGHT, or CENTER. |
|
bitmap |
The bitmap to display in the widget. If the image option is given, this option is ignored. |
|
image |
The image to display in the widget. If specified, this takes precedence over the text and bitmap options. |
|
Methods | None except from standard Tkinter method. |
Description |
The Button widget is a standard Tkinter widget used to implement various kinds of buttons. Buttons can contain text or images, and you can associate a Python function or method with each button. When the button is pressed, Tkinter automatically calls that function or method. |
|
---|---|---|
Options | anchor | Controls where in the button the text (or image) should be located. |
command | A function or method that is called when the button is pressed. The callback can be a function, bound method, or any other callable Python object. | |
state | The button state: Normal, Active or Disabled. | |
text | The text to be displayed in the button. The text can contain newlines. If the bitmap or image options are used, this option is ignored. | |
Methods | Flash( ) | Redraws the button several times, alternating between active and normal appearance. |
Invoke( ) | Calls the command associated with the button. |
Description |
The Entry widget is a standard Tkinter widget used to enter or display a single line of text. |
|
---|---|---|
Options | show | Controls how to display the contents of the widget. If non-empty, the widget displays a string of characters instead of the actual contents. To get a password entry widget, use "*" |
state | The Entry state: Normal or Disabled | |
Methods | insert(index,text) | Insert text at the given index. Use insert(INSERT, text) to insert text at the cursor, insert(END, text) to append text to thewidget. |
delete(index), delete(from,to) |
Delete the character at index, or within the given range. Use delete(0, END) to delete all text in the widget. | |
get( ) | Get the current contents of the entry field in a string. |
Description |
The Radiobutton is a standard Tkinter widget used to implement one-of-many selections. Radiobuttons can contain text or images, and you can associate a Python function or method with each button. When the button is pressed, Tkinter automatically calls that function or method. Each group of Radiobutton widgets should be associated with a single variable. Each button then represents a single value for that variable. |
|
---|---|---|
Options | command | A function or method that is called when the button is pressed. The callback can be a function, bound method, or any other callable Python object. |
text | The text to display in the button. The text can contain newlines. If the bitmap or image options are used, this option is ignored. | |
value | The value to assign to the associated variable when the button is pressed. | |
variable | Associates a Tkinter variable to the button. When the button is pressed, the variable is set to value. Explicit changes to the variable are automatically reflected by the buttons. | |
Methods | select( ) | Selects the button |
deselect( ) | Deselects the button | |
invoke( ) | Calls the command associated with the button |
Description |
The Checkbutton widget is a standard Tkinter widgets used to implement on-off selections. Checkbuttons can contain text or images, and you can associate a Python function or method with each button. When the button is pressed, Tkinter automatically calls that function or method. Each Checkbutton widget should be associated with a variable |
|
---|---|---|
Options | command | A function or method that is called when the button is pressed. The callback can be a function, bound method, or any other callable Python object. |
text | The text to display in the button. The text can contain newlines. If the bitmap or image options are used, this option is ignored. | |
offvalue, onvalue | The values corresponding to a non-checked or checked button, respectively. Defaults are 0 and 1. | |
variable | Associates a Tkinter variable to the button. When the button is pressed, the variable is set to value. Explicit changes to the variable are automatically reflected by the buttons. | |
Methods | select( ) | Select the button |
deselect( ) | Deselects the button | |
invoke( ) | Calls the command associated with the button | |
toggle( ) | Toggles the selection state |
Description |
The Menu widget is used to implement toplevel, pulldown, and popup menus. |
|
---|---|---|
Options | postcommand | If given, this callback is called whenever Tkinter is about to display this menu. If you have dynamic menus, use this callback to update their contents. |
tearoff | If set, menu entry 0 will be a "tearoff entry", which is usually a dashed separator line. If the user selects this entry, Tkinter creates a small Toplevel with a copy of this menu. | |
tearoffcommand | If given, this callback is called when this menu is teared off. | |
title | Specifies the title of menu | |
Methods | add(type, options...) | Add (append) an entry of the given type to the menu. The type argument can be one of "command", "cascade" (submenu), "checkbutton", "radiobutton", or "separator". |
insert(index, type, options...) | Same as add and friends, but inserts the new item at the given index. | |
entryconfig(index, options...) | Reconfigures the given menu entry. Only the given options are changed; the rest are left as is | |
delete(index) | Deletes one or more menu entries |
Description |
The message widget is used to display multiple lines of text. It's very similar to a plain label, but can adjust its width to maintain a given aspect ratio. |
|
---|---|---|
Options | None except from standard Tkinter options. | |
Methods | None except from standard Tkinter method. |
Description |
The Text widget provides formatted text display. It allows to display and edit text with various styles and attributes. The widget also supports embedded images and windows. |
|
---|---|---|
Options | setgrid | If true, Tkinter attempts to resize the window containing the text widget in full character steps (based on the font option). |
spacing1, spacing2, spacing3 | Spacing to use above the first line, between the lines and after the last line, respectively, in a block of text. Default is 0 (no extra spacing). | |
wrap | Word wrap mode. Use one of NONE, CHAR, or WORD. Default is NONE. | |
Methods |
insert(index, text) insert(index, text, tags) |
Inserts text at the given position (typically INSERT or END). If you provide one or more tags, they are attached to the new text. |
delete(index), delete(start, stop) |
Deletes the character (or embedded object) at the given position, or all text in the given range. Any marks within the range are moved to the beginning of the range. | |
index(index) | Returns the "line.column" index corresponding to the given index |
Description |
This widget is used to implement scrolled listboxes, canvases, and text fields. |
|
---|---|---|
Options | orient | Defines how to draw the scrollbar. Use one of HORIZONTAL or VERTICAL. Default is VERTICAL. |
command |
Used to update the associated widget. This is typically the
xview or yview method of the scrolled widget. If the user drags the scrollbar slider, the command is called as callback(MOVETO, offset) where offset 0.0 means that the slider is in its topmost (or leftmost) position, and offset 1.0 means that it is in its bottommost (or rightmost) position. If the user clicks the arrow buttons, or clicks in the trough, the command is called as callback(SCROLL, step, what). The second argument is either "-1" or "1" depending on the direction, and the third argument is UNITS to scroll lines (or other units relevant for the scrolled widget), or PAGES to scroll full pages. |
|
Methods | get( ) | Returns the relative offset for the upper (leftmost) and lower (rightmost) end of the scrollbar slider. Offset 0.0 means that the slider is in its topmost (or leftmost) position, and offset 1.0 means that it is in its bottommost (or rightmost) position. |
set(lo, hi) | Moves the slider to a new position |
Description |
The Listbox widget is a standard Tkinter widget used to display a list of alternatives. The listbox can only contain text items, and all items must have the same font and colour. Depending on the widget configuration, the user can choose one or more alternatives from the list. |
|
---|---|---|
Options | selectmode |
Selection mode. One of SINGLE, BROWSE, MULTIPLE, or EXTENDED.
Default is BROWSE. Use MULTIPLE to get checklist behavior,
EXTENDED if the user usually selects one item, but sometimes
would like to select one or more ranges of items. See the patterns section for more information. |
xscrollcommand, yscrollcommand | Used to connect a listbox to a scrollbar. These options should be set to the set methods of the corresponding scrollbars. | |
Methods |
delete(index), delete(first, last) |
Deletes one or more items. Use delete(0, END) to delete all items in the list. |
get(index) | Gets one or more items from the list. This function returns the string corresponding to the given index (or the strings in the given index range). Use get(0, END) to get a list of all items in the list. Use ACTIVE to get the active (underlined) item. | |
insert(index, items) | Inserts one or more items at given index (this works as for Python lists; index 0 is before the first item). Use END to append items to the list. Use ACTIVE to insert items before the the active (underlined) item. | |
size( ) | Returns the number of items in the list. The valid index range goes from 0 to size( )-1. |
Description |
The The Scale widget is a standard Tkinter widget which manipulates much alike a horizontal scrollbar. However, in a scale, each position is numbered within a defined range which can bear a specific meaning. |
|
---|---|---|
Options | From(value), to(value) | Specifies the range of value for the scale |
orient | Defines the orientation of the scale. | |
command | A function or method that is called when the button is pressed. The callback can be a function, bound method, or any other callable Python object. | |
Methods | get( ) | Gets the current scale value. Tkinter returns an integer if possible, otherwise a floating point value is returned. |
set(value) | Sets the scale value. |
*see detailed presentation below
As mentioned earlier, font in widgets is defined through the font option in the standard Tkinter widget interface. To properly define a font for widgets, this has to be specified using a font descriptor which is a n-tuple: (family, size, option1, option2 ). The first element, family, specifies the font name. Tkinter supports a vast variety of font names on different platform such as Arial, Times New Roman, etc. It also recognizes specific system fonts like 6x10. The second element of the tuple is the size, specified via an integer. The options that follows the size parameter within the tuple are used to describe the style of the font. This last can be normal, bold, underlined, italic, etc.
Widgets colour display can be configured
via the colour option. The option can be specified using a
common colour name such as red, blue, green, etc. However,
Tkinter includes a color database which maps color names to
the corresponding RGB values, therefore, it also recognizes
more exotic names such as mocassin, peachpuff, etc.
If desired, the user can enter his or her own colour using
RGB format. The format is #RRGGBB, which is then capable of
having 65536 different kind of colours.
Tkinter
has a special variable class that all other variable subclasses
inherit from. Various Tkinter widgets have options that rely on the
Variable class, such as the variable option for
Radiobuttons, the textvariable option for the Label, etc. It should
be noted that variable options only take parameters which are
instances of the Variable class (or one of its subclasses). If a
regular Python variable is passed as parameter, the it will never
receive the appropriate value. That is, the store and retrieve calls
will silently fail. Moreover, it must be mentioned that the set( )
method does not do type or range checking on value, it simply stores
it, even if it is not of the proper type. Therefore, it cannot be
used as is inside a try..execute block to validate data. The get( )
method, however, will fail if the value associated with the variable
is erroneous. However, at this point, the previous value is lost.
When the Tkinter variables are used for simple tasks, they do not behave
differently than the regular Python variables, apart the fact that
their values have to be handled through method calls, such as get( )
and set( ). The choice behind the implementation of this master
variable class is therefore not obvious. However, by taking a closer
look at what the Variable class offers, the motivation behind it
becomes much more apparent. Tkinter variables provide, in true
Tkinter style, the possibility to add a callback wich will be
executed when read and write operations are performed on the
variable, and also when the value associated with the variable is
undefined. This allows, for example, to bind a StringVar( ) instance
to a Label widget, which then automatically updates its caption when
the value of the variable changes.
Tkinter variables have a __del__ method which frees their associated memory
when they are no longer referenced. Therefore, one should always keep
a reference to a Tkinter variable instance as a global reference or a
class variable. While this is almost always the case, it might make a
difference in some very specific situations.
The Variable class provides the following methods:
Private Methods | |
---|---|
__init__(self, master=None) | Constructor (an exception is raised if the master is None, since the Constructor calls master.tk) |
__del__(self) | Destructor |
__str__(self) | Returns the name of the variable. |
Public Methods | |
set(self,value) | Assigns value to the variable |
trace_variable(self, mode, callback) | Assigns a callback to the variable. Mode must be one of r, w, or u. Depending on the value of mode, callback is executed when a value is read from the variable, written to the variable or when its value becomes undefined, respectively. This method returns the name of the callback, which is needed to delete it. |
trace_vdelete(self, mode, cbname) | Deletes the callback with the specified name and mode. |
trace_vinfo(self) | Returns a list of all of the callback names associated with the variable and their respective modes (each mode callback name pair is stored as a tuple). |
The Variable class does not implement the get( ) method. It is only the base class for all variables, and is not intended for direct use. Instead, Tkinter provides 4 descendants of the Variable class, each implementing its specific get( ) method:
Geometry management consists of placing widget
placement and size on the screen. Tkinter provides three geometry
managers, therefore allowing the user to quickly and efficiently
build user interfaces, with maximal control over the disposition
of the widgets. The geometry managers also allow the user make
abstraction of the specific implementation of the GUI on each
platform that Tkinter supports, thus making the design truly portable.
Geometry management implies a great deal of negotiations between the
different widgets and their containers, as well as the windows they
are placed in. Geometry management is not only responsible for the
precise position and size of a widget, but also of this widgets
position and size relative to the other widgets, and of renegotiating
these factors when conditions change, for example when the window is
resized.
The packer is the quickest way to design user
interfaces using Tkinter. It allows the user the place the widgets relative
to their contained widget. It is the most commonly used geometry manager
since it allows a fair amount of flexibility.
The packer positions the slave widgets on the master widget (container)
from the edges to the center, each time using the space left in the
master widget by previous packing operations (see demo).
Options for the Pack geometry manager:
Option | Values | Effect |
---|---|---|
expand |
|
Specifies whether the widget should expand to fill the available space (at packing time and on window resize) |
fill |
|
Specifies how the slave should be resized to fill the available space (if the slave is smaller than the available space) |
side |
|
Specifies which side of the master should be used for the slave. |
in_(in) | Widget |
Packs the slaves inside the widget passed as a parameter.
This option is usually left out, in which case the widgets
are packed in their parent. Restriction: widgets can only be packed inside their parents or descendants of their parent. |
padx,pady | Integer values | Specifies the space that must be left out between two adjacent widgets. |
ipadx, ipady | Integer values | Specifies the size of the optional internal border left out when packing. |
anchor |
|
Specifies where the widget should be placed in the space that it has been allocated by the packer, if this space is greater than the widget size. Default is CENTER. |
Methods supported by the Pack geometry manager:
Method | Effect |
---|---|
pack(option=value,
) pack_configure(option=value, ) |
Packs the widget with the specified options. |
pack_forget( ) | The widget is no longer managed by the Packer, but is not destroyed. |
pack_info( ) | Returns a dictionary containing the current options. |
pack_slaves( ) | Returns a list of widget IDs, in the packing order, which are slaves of the master widget. |
Python program demonstrating the use of the Pack geometry manager:
The grid geometry manager is used for more complex
layouts. It allows the user to virtually divide the master widget
into several rows and columns, which can then be used to place slave
widgets more precisely. The packer geometry manager would require the
use of multiple nested frames to obtain the same effect.
The grid geometry manager allows the user to build a widget grid using an
approach that is very similar to building tables using HTML. The user
builds the table specifying not only the row and column at which to
place the widget, but also the rwo span and column span values to use
for the widget. In addition to that, the sticky option can allow
almost any placement of the widget inside a cell space that is bigger
than the widget itself. Combinations of values for the sticky option
also allow to resize the widget, such as EW value, equivalent to an
expand option combined with a fill=X for the packer.
Options for the Grid geometry manager:
Option | Values | Effect |
---|---|---|
row, column | Integer values | Specifies where the widget should be positioned in the master grid. |
rowspan, columnspan | Integer values | Specifies the number of rows / columns the widget must span across. |
in_(in) | Widget |
Use the widget passed as a parameter as the master. This
option is usually left out, in which case the widgets are packed
in their parent.
Restriction: widgets can only be packed inside their parents or descendants of their parent. |
padx, pady | Integer values | Specifies the space that must be left out between two adjacent widgets. |
ipadx, ipady | Integer values | Specifies the size of the optional internal border left out when packing. |
sticky |
|
Specifies where the widget should be placed in the space that it has been allocated by the grid manager, if this space is greater than the widget size. Default is to center the widget, but the grid( ) method does not support the CENTER value for sticky. |
Methods supported by the Grid geometry manager:
Method | Effect |
---|---|
grid(option=value,
), grid_configure(option=value, ) |
Places the widget in a grid, using the specified options. |
grid_forget( ), grid_remove( ) | The widget is no longer managed by the Grid, but is not destroyed. |
grid_info( ) | Returns a dictionary containing the current options. |
grid_slaves( ) | Returns a list of widget IDs which are slaves of the master widget. |
grid_location(x,y) | Returns a tuple (column, row) which represents the cell in the grid that is closest to the point (x, y). |
grid_size( ) | Returns the size of the grid, in the form of a tuple (column, row), in which column is the index of the first empty column and row the index of the first empty row. |
It is important to note that empty rows and columns
are not displayed by the grid geometry manager, even if a minimum size
is specified.
Note: The grid manager cannot be used in combination with the pack
manager, as this results in an infinite negociation loop.
Python program demonstrating the use of the Grid geometry manager:
The place geometry manager is the more powerful
manager of all since it allows exact placement of the widgets inside
a master widget (container). However, it is more difficult to use and
usually represent a great amount of overhead thats is generally
not needed.
The Place geometry manager allows placement of widgets using either
exact coordinates (with the x and y options), or as a percentage
relative to the size of the master window (expressed as a float in the
range [0.0, 1.0]) with the relx and rely options. The same principle
holds for the widget size (using width / height and/or relwidth /
relheight).
The options supported by the place geometry manager are as follows:
Option | Type | Effect |
---|---|---|
anchor |
String, one of:
|
Specifies which part of the widget should be placed at the specfied position. |
bordermode | INSIDE, OUTSIDE | Specifies if the outside border should be taken into consideration when placing the widget. |
in (in_) | Widget | Places the slave in the master passed as the value for this option. |
relwidth, relheight | Float [0.0, 1.0] | Size of the slave widget, relative to the size of the master. |
relx, rely | Float [0.0, 1.0] | Relative position of the slave widget. |
width, height | integer | Absolute width and height of the slave widget. |
x, y | Integer | Absolute position of the slave widget. |
Python program demonstrating the use of the Place geometry manager:
Tkinter provides an easy and convenient way to handle events by allowing callback functions to be associated with any event for any widget. This is a very flexible approach, compared to some other GUI toolkits. Tkinter can handle the following event types:
Events have the following attributes:
Attrib. | Explanations |
---|---|
serial | serial number of the event |
num |
number of the mouse button pressed (ButtonPress, ButtonRelease) (1=LEFT, 2=CENTER, 3=RIGHT, etc.) |
focus | boolean which indicates whether the window has the focus (Enter, Leave) |
height | height of the exposed window (Configure, Expose) |
width | width of the exposed window (Configure, Expose) |
keycode | keycode of the pressed key (KeyPress, KeyRelease) |
state | state of the event as a number (ButtonPress, ButtonRelease, Enter, KeyPress, KeyRelease, Leave, Motion) |
time | time at which the event occurred. Under Microsoft Windows, this is the value returned by the GetTickCount( ) API function. |
x | x-position of the mouse relative to the widget |
y | y-position of the mouse relative to the widget |
x_root | x-position of the mouse on the screen relative to the root (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion) |
y_root | y-position of the mouse on the screen relative to the root (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion) |
char | pressed character (as a char)(KeyPress, KeyRelease) |
send_event |   |
keysym | keysym of the the event as a string (KeyPress, KeyRelease) |
keysym_num | keysym of the event as a number (KeyPress, KeyRelease) |
type | type of the event as a number |
widget | widget for which the event occurred |
delta | delta of wheel movement (MouseWheel) |
There are 3 ways to bind events to widgets in Tkinter:
When
an event occurs in Tkinter, the event callbacks are called according
to their level of specificity. The most specific event handler is
always used, the others are not called (eg when Return is pressed, a
callback associated with the <Return> event will be executed
and one associated with the <KeyPress> event will not be called
in the case where both have been bound to the same widget). Moreover,
the callbacks for the 4 different levels of Tkinters event
handling will be called in sequence, starting with the widget level,
then the Toplevel, the class and then the Application.
If, at a given level, the callback handling must stop, it can be
accomplished by returning the string break from the
callback. This will prevent any other callbacks from being executed
for a given event.
In Tkinter, all event handling requires a string description of the
event to be bound. Each of these strings can be divided into three
sections, and is usually enclosed in angular brackets. The general
format is as follows:
Python program demonstrating the Event handling in Tkinter:
The canvas widget provides the basic graphics facilities
for Tkinter, and so more advanced functions. Drawing on the canvas is done
by creating various items on it. It is important to note at this stage that
items are not widgets, even though they are similar in many ways.
Each item on a canvas is enclosed by a bounding box, which is
definied using 2 points: the top-left corner and the bottom-right
corner of the box. Tkinter uses two coordinate systems
simultaneously: the canvas coordinate system and the window
coordinate system. Both systems express positions relative to the
top-left corner, with X-coordinates increasing to the right and
Y-coordinates increasing downwards. However, the origin for the two
systems is different. The window system expresses the coordinates by
placing the origin at the top-left corner of the visible portion of
the canvas, while the canvas system places its origin at the
top-corner of the canvas widget, even it is not visible. The
difference is important when handling mouse events bound to the
canvas since the event object receives its coordinates in the window
system. Luckily, the canvas widget provides the necessary methods to
convert coordinates to the canvas system, through calls to the
canvasx( ) and canvasy( ) methods.
The Tkinter canvas supports the following standard items (more can also
be added):
Apart from their bounding box, all canvas items can be referenced using their unique item ID, which is assigned at the time they are created, and is returned by any of the item constructors. Tkinter also provides a usefull way of working with items: the tags. A number of strings, called tags, can be associated with a canvas item, and more than one item can have the same tag. Items can then be referenced using those tags (see 7 for details). Canvas items can also be bound to events, using the tag_bind( ) method.
The canvas widget supports the following options, in addition to the inherited options from Widget:
Option | Values | Effect |
---|---|---|
closeenough | Float | Specifies how close to an item the mouse cursor has to be before it is considered to be over it (a higher value means that the item will selected more readily). Default is 1. |
confine | Boolean | If TRUE (default), it is not allowed to set the canvas view outside of the region defined by scrollregion. |
scrollregion | List of 4 coordinates | Defines the region that is considered to be the boundary of all items in the canvas. It is used for scrolling purposes, in order to limit the scroll actions to a definite area. |
xscrollcommand, yscrollcommand | function | Specifies which function is used to interact with a scrollbar. |
xscrollincrement, yscrollincrement | distance | Specifies the increment for horizontal and vertical scrolling, respectively. |
The canvas widget supports the following methods:
Function | Return type | Effect |
---|---|---|
Item Creation and Manipulation | ||
create_arc(bbox, options) | Item ID | Creates an arc canvas item and returns its item ID. |
create_bitmap(position, options) | Creates a bitmap canvas item and returns its item ID. | |
create_image(position, options) | Creates an image canvas item and returns its item ID. | |
create_line(coords, options) | Creates a line canvas item and returns its item ID. | |
create_oval(bbox, options) | Creates an oval canvas item and returns its item ID. | |
create_polygon(coords, options) | Creates a polygon canvas item and returns its item ID. | |
create_rectangle(bbox, options) | Creates a rectangle canvas item and returns its item ID. | |
create_text(position, options) | Creates a text canvas item and returns its item ID. | |
create_window(position, options) | Places a Tkinter widget in a canvas window item and returns its item ID. | |
delete(items) | Deletes all matching items, if any. | |
itemcget(item, option) | Returns the current value for an option from a canvas item. | |
itemconfig(item, options), itemconfigure(item, options) |
Modifies one or more options for all matching items. | |
coords(item) | Returns a tuple containing the coordinates for the item. | Returns the coordinates for the given item. |
coords(item, x0, y0, x1, y1, ..., xn, yn) | Changes the coordinates for all matching items. | |
bbox(items), bbox( ) | Tuple | Returns the bounding box for the given items. If the specifier is omitted, the bounding box for all items are returned. |
canvasx(screenx), canvasy(screeny) | Float | Converts a window coordinate to a canvas coordinate. |
tag_bind(item, sequence, callback) , tag_bind(item, sequence, callback, "+") |
Adds an event binding to all matching items. Using the + option, it adds the binding to the previous ones, otherwise all previous bindings are replaced. | |
tag_unbind(item, sequence) | Removes the binding, if any, for the given event sequence on all the matching items. | |
type(item) |
String, one of:
|
Returns the type of the given item. |
lift(item) , tkraise(item) / lower(item) |
Moves the given item to the top / bottom of the canvas stack. If multiple items match, they are all moved while preserving their relative order. | |
move(item, dx, dy) | Moves all matching items dx canvas units to the right, and dy canvas units downwards. Negative coordinates specify a displacement in the other direction. | |
scale(item, xscale, yscale, xoffset, yoffset) | Scales matching items according to the given scale factors. The coordinates for each item are first moved by -offset, then multiplied with the scale factor, and then moved back again. | |
Tag Manipulation | ||
addtag_above(newtag, item) | Adds newtag to the item just above the given item in the stacking order. | |
addtag_all(newtag) | Adds newtag to all items on the canvas. This is a shortcut for addtag_withtag(newtag, ALL). | |
addtag_below(newtag, item) | Adds newtag to the item just below the given item, in the stacking order. | |
addtag_closest(newtag, x, y) | Adds newtag to the item closest to the given coordinate. See find_closest for more information. | |
addtag_enclosed(newtag, x1, y1, x2, y2) | Adds newtag to all items completely enclosed by the given rectangle. | |
addtag_overlapping(newtag, x1, y1, x2, y2) | Adds newtag to all items enclosed by or touching the given rectangle. | |
addtag_withtag(newtag, tag) | Adds newtag to all items having the given tag. | |
dtag(item, tag) | Removes the given tag from all matching items. If the tag is omitted, all tags are removed from the matching items. It is not an error to give a specifier that doesn't match any items. | |
gettags(item) | Tuple | Returns all tags associated with the item. |
Search methods | ||
They correspond to the addtag_XYZ methods, but are named find_XYZ. | ||
Printing | ||
postscript(options) | Generates a postscript representation of the canvas items. Images and widgets are not included in the output. |
Just like widgets, canvas items also have a number of options. All items can, for example, have their fill color and their border color changed, or set to transparent. The complete list can be found at www.python.org.
Python program demonstrating the Canvas widget:
Tags represent a very powerful, yet very easy to use
feature of Tkinter. The idea behind them is really simple, and it is
not surprising to see them used in the implementation of sereval widgets,
such as the Canvas and the Text widgets. In the Text widget, tags can be
used to mark parts of the text for easier reference. In the canvas widget,
the tags serve to mark on or more widgets for future reference. This
discussion will focus on the use of tags in the Canvas widget.
As was previously mentioned, tags can be used in a many:many
relationship: multiple canvas items can have the same tag and one
item can have multiple different tags. This can be used to create
groups of widgets. The most interesting point to make about tags is
that canvas methods acting on items can receive as parameters item
IDs or tags interchangeably. One might wonder what happens to methods
that only apply to a single item at a time (such as bbox( )). Tkinter
provides the best possible approach for these situations by only
taking the first item that matches the specified tag. When the method
must be applied to several or all of the items having the tag,
Tkinter also provides an easy solution. The find_withtag( ) method
produces a list of all items having the tag passed as only parameter.
This information can then be used inside a simple for loop.
In addition to the tags that are added by the user, Tkinter supports two
special, built-in tags, CURRENT and ALL. As expected, the ALL tag
identifies all items in the canvas, while the CURRENT tag is
automatically updated, indicating the item over which the mouse
pointer is located. Therefore, a call to canvas.find_all( ) is the
same as a call to find_withtag(ALL). Those two tags are simply handled like
any other tag. The CURRENT constant simply evaluates to the string
current, while the ALL constant evaluates to all.
Therefore, those tags should not be used by the
user. Doing so will not raise any exception, but setting these tags
manually will silently fail since they are managed by Tkinter.
Moreover, the tag_bind( ) and tag_unbind( ) methods can be used to associate
event callbacks to canvas items, thus freeing the canvas from the
task of dispatching the event to the proper item(s). These methods
reduce the gap between canvas items and widgets.
Python program demonstrating the use of tags for the Canvas widget: