This document is for beginners.
It assumes you know some Perl,
and have it and Tk running.
If you are not currently reading this document courtesy of the widget demonstration program,
please be sure to run widget,
as it will show you the various widget types supported by Tk and how to use them.
widget should be installed in your default path,
so type widget at a command prompt.

Tk GUI programming is event-driven.
(This may already be familiar to you.) In event-driven programs,
the main GUI loop is outside of the user program and inside the GUI library.
This loop - initiated by calling MainLoop - watches all events of interest and activates the correct handler procedures to handle these events.
Some of these handler procedures may be user-supplied; others will be part of the library.

For a programmer,
this means that you're not watching what is happening; instead,
you are requested by the toolkit to perform actions whenever necessary.
So,
you're not watching for 'raise window / close window / redraw window' requests,
but you tell the toolkit which routine will handle such cases,
and the toolkit will call the procedures when required.
These procedures are known as callbacks,
and some of them you write yourself.

Perl programs that use Tk need to include use Tk.
A program should also use use strict and the -w switch to ensure the program is working without common errors.

Any Perl/Tk application starts by creating the Tk MainWindow.
You then create items inside the MainWindow,
and/or create new windows called Toplevels that also contain child items,
before starting the MainLoop,
which is the last logical statment in your program.
You can also create more items and windows while you're running,
using callbacks.
Items are only shown on the display after they have been arranged by a geometry manager like pack; more information on this later.
MainLoop starts the GUI and handle all events.
That's all there is to it!
A trivial one-window example is shown below:

Please run this example. It shows you two widget types, a Label and a Button, and how they are packed. When clicked, the Button widget invokes the callback specified by the -command option. Finally, note the typical Tk style using -option => value pairs.

Tk windows and widgets are hierarchical, i.e. one window includes one or more other windows. You create the first Tk window using MainWindow->new. This returns a window handle, assigned to $mw in the example above. Keep track of the main handle, commonly called a widget reference.

You can use any Tk handle to create child widgets within the window (or widget). This is done by calling the Tk constructor method on the variable. In the example above, the Label method called from $mw creates a Label widget inside the MainWindow. In the constructor call, you can specify various options; you can later add or change options for any widget using the configure method, which takes the same parameters as the constructor. The one exception to the hierarchical structure is the Toplevel constructor, which creates a new outermost window.

After you create any widget (other than the MainWindow or Toplevels, you must render it by calling pack. (This is not entirely true; more later)). If you do not need to refer to the widget after construction and packing, call pack off the constructor results, as shown for the Label and Button in the example above. Note that the result of the compound call is the result of pack, which is a valid Tk handle.

Windows and widgets are deleted by calling destroy on them; this will delete and un-draw the widget and all its children.

Most graphical interfaces are used to set up a set of values and conditions, and then perform the appropriate action. The Tk toolkit is different from your average text-based prompting or menu driven system in that you do not collect settings yourself, and decide on an action based on an input code; instead, you leave these values to your toolkit and only get them when the action is performed.

The slightly larger example below shows how to do this in Tk. Note the use of callbacks. Note, also, that Tk handles the values, and the subroutine uses the method get to get at the values. If a user changes his mind and wants to change the font again, the application never notices; it's all handled by Tk.

In the examples above, you must have noticed the pack calls. This is one of the more complicated parts of Tk. The basic idea is that any window or widget should be subject to a Tk geometry manager; the packer is one of the placement managers, and grid is another.

The actions of the packer are rather simple: when applied to a widget, the packer positions that widget on the indicated position within the remaining space in its parent. By default, the position is on top; this means the next items will be put below. You can also specify the left, right, or bottom positions. Specify position using -side => 'right'.

Additional packing parameters specify the behavior of the widget when there is some space left in the Frame or when the window size is increased. If widgets should maintain a fixed size, specify nothing; this is the default. For widgets that you want to fill up the current horizontal and/or vertical space, specify -fill => 'x', 'y', or 'both'; for widgets that should grow, specify -expand => 1. These parameters are not shown in the example below; see the widget demonstration.

If you want to group some items within a window that have a different packing order than others, you can include them in a Frame. This is a do-nothing window type that is meant for packing or filling (and to play games with borders and colors).

Most real applications require more than one window. As you just saw, you can create more outermost windows by using a Toplevel widget. Each window is independent; destroying a Toplevel window does not affect the others as long as they are not a child of the closed Toplevel. However, exiting the MainWindow will destroy all remaining Toplevel widgets and end the application. The example below shows a trivial three-window application:

So far, all callback routines shown called a user procedure. You can also have a callback routine call another Tk routine. This is the way that scroll bars are implemented: scroll-bars can call a Tk item or a user procedure, whenever their position has changed. The Tk item that has a scrollbar attached calls the scrollbar when its size or offset has changed. In this way, the items are linked. You can still ask a scrollbar's position, or set it by hand - but the defaults will be taken care of.

The example below shows a Listbox with a scroll bar. Moving the scrollbar moves the Listbox. Scanning a Listbox (dragging an item with the left mouse button) moves the scrollbar.

One of the most powerful widgets in Tk is the Canvas window. In a Canvas window, you can draw simple graphics and include other widgets. The Canvas area may be larger than the visible window, and may then be scrolled. Any item you draw on the canvas has its own id, and may optionally have one or more tags. You may refer to any item by its id, and may refer to any group of items by a common tag; you can move, delete, or change groups of items using these tags, and you can bind actions to tags. For a properly designed (often structured) Canvas, you can specify powerful actions quite simply.

In the example below, actions are bound to circles (single click) and blue items (double-click); obviously, this can be extended to any tag or group of tags.

Perl/Tk follows Perl's model of handling Unicode. That is, if a string is correctly flagged as a "character" string in the sense like described in "TERMINOLOGY" in Encode, then Perl/Tk will very probably display and handle this string correctly.

Note that every variable which is passed somehow into a Perl/Tk method will be implicitely changed into an internally utf8-flagged variable. Semantically nothing changes, as the series of codepoints stays the same, but things will change when variables with high-bit iso-8859-1 characters will be passed to the "outer" world. In this case you have to explicitely mark the encoding of your output stream if using IO, or encode the variables using Encode for other style of communication.

This is the theory, now some examples.

If you use non-iso-8859-1 characters in the source code, then use either the use utf8; or use encoding 'encodingname' pragma:

Likewise, the encoding must be specified for all data which is read from Tk widgets and that shall be output into a file. For the output, the encoding should be always specified, even if it is iso-8859-1:

Note that Tk is Unicode-capable. So you need to be prepared that the user has the appropriate input methods activated to enter non-ascii characters. If an output encoding is used which does not cover the whole of Unicode codepoints then a warning will be issued when writing the file, like this:

"\x{20ac}" does not map to iso-8859-1 at /usr/local/lib/perl5/site_perl/5.8.8/mach/Tk.pm line 250.

Also, the same hexadecimal notation will be used as replacements for the unhandled characters.

Handling encoding in I/O is pretty simple using the encoding PerlIO layer, as described above. In other cases, such as when dealing with databases, encoding the data usually has to be done manually, unless the database driver has some means for automatically do this for you. So when working with a MySQL database, one could use:

Unfortunately, there are still places in Perl ignorant of Unicode. One of these places are filenames. Consequently, the file selectors in Perl/Tk do not handle encoding of filenames properly. Currently they suppose that filenames are in iso-8859-1 encoding, at least on Unix systems. As soon as Perl has a concept of filename encodings, then Perl/Tk will also implement such schemes.