TCL TK Tutorial
TCL TK Tutorial
Table of Contents
If you're viewing this document online, you can click any of the topics below to link directly to that section.
4. Tk commands ...........................................................
17
22
6. Tcl/Tk extensions.......................................................
26
29
Page 1 of 30
ibm.com/developerWorks
Page 2 of 30
ibm.com/developerWorks
The which command returns the path to the specified executable. If you don't see results
similar to these, then you'll want to head over to the Scriptics Tcl/Tk page to download and
build your own copy. Of course, the absence of these programs on your system is not
indicative of any problem. Unlike Perl, Tcl/Tk is generally not regarded as essential to the
operation of Linux. Every distribution I'm aware of ships with a version of Tcl/Tk and the most
popular extensions as a part of the CDROM or online repository collection. From these
sources, the tools are generally fairly easy to install. If you have difficulty, contact the
publisher of your GNU/Linux software.
Page 3 of 30
ibm.com/developerWorks
Page 4 of 30
ibm.com/developerWorks
#!/usr/bin/tclsh
# filename hello2.tcl
# This program code shows
Metacharacters are those characters or character
# metacharacter usage
pairs that have special meaning in the context of
puts stdout "Hello, World! \a"
puts stdout {Hello, World! \a}
the Tcl/Tk environment, including grouping
set Pints 6
statements, encapsulating strings, terminating
set Days 7
statements
and more, as delineated in the
puts stdout "The answer to the
\
following table. Many of these are demonstrated in
universe is [eval $Pints * $Days]!\n"
***
the code listing to the left. One special feature to
~/tcltk$ ./hello2.tcl
notice is the difference in output when curly braces
Hello, World!
(which prevent substitution and expansion) are
Hello, World! \a
used in place of double quotes.
The answer to everything is 42!
Tcl metacharacters
Character(s)
#
; or newline
Name
Name(idx)
Name(j,k,l...)
"string"
{string}
[string]
\char
\
Used as
Comment
Statement separators
A variable (case sensitive)
Array Variable
Multidimensional Array
Quoting with substitution
Quoting without substitution
Command substitution
Backslash substitution
Line continuation (at end of line)
#!/usr/bin/tclsh
#
# Demonstrate global variables
# and backslash substitution
if {$argc >= 1} {
Several global variables exist (and are pre-defined,
set N 1
if not null in the current context) when a Tcl/Tk
foreach Arg $argv {
puts stdout "$N: $Arg\n"
script begins running. These variables permit
set N [expr $N + 1] access to the operating environment as follows:
if {$Arg == "ring"} {argc is the count of arguments to the script, not
puts stdout "\a"
counting the name as invoked. argv is a list (not an
}
array) of arguments. argv0 is the invoked filename
}
} else {
(which may be a symlink). env is an array that is
puts stdout "$argv0 on \ indexed by the names of the current shell's
X Display $env(DISPLAY)\n"
environment variables. errorCode stores
}
information about the most recent Tcl error, while
***
errorInfo contains a stack trace from the same
~/tcltk$ ./hello3.tcl
Page 5 of 30
ibm.com/developerWorks
Substitution
Bell
Backspace
Formfeed
Newline
Carriage return
Horizontal tab
Vertical Tab
Space
Octal value
Hexadecimal value
Echo 'c'
Backslash
Page 6 of 30
Area = 78.5398163397
ibm.com/developerWorks
...
#
# parse command line switches
The looping commands in Tcl are while, for, and
set Optimize 0
foreach. The conditional (branching) commands
set Verbose 0
foreach Arg $argv {
are if/then/else/elsif and switch. Modifiers for the
switch -glob -- $Arg preceding
{
commands are break, continue, return,
-o* {set Optimize 1}
and
error.
Finally,
the catch command is provided
-v* {set Verbose 1}
for
error
handling.
default {
error "Unknown $Arg"
}
if/then/else/elsif was demonstrated in previous
}
panels. While then is a part of the formal syntax, it
}
is most often observed in absentia.
set LineCount 0
while {[gets stdin Line] >= 0} {
# to confuse Vanna White...
In the example at the left, a switch command is fed
Remove_Vowels $Line \
the command line arguments by the foreach
$Optimize $Verbose
incr LineCount
}
return LineCount
...
Page 7 of 30
ibm.com/developerWorks
~/tcltk$ tclsh
% set Phrase "hello, world!"
hello, world!
% string toupper $Phrase
HELLO, WORLD!
Strings are the fundamental data type in Tcl. The
% string totitle $Phrase
string command is really a variety of commands,
Hello, world!
% string match ello $Phrase gathered under one umbrella. In use, string reads
0
much like the application of specific object
% string match *ello* $Phrasemethods from OOP programming, as you can see
1
in the example on the left.
% string length $Phrase
14
% append Phrase "Nice day, eh?"
The informational string commands are length and
hello, world!
bytelength (which can differ, depending on
Nice day, eh?
character set). Comparisons that return boolean
% string toupper $Phrase
values (1 or 0) are compare, equal, and match.
HELLO, WORLD!
NICE DAY, EH?
Pattern matching here is accomplished by
% string wordend $Phrase 7 "globbing", the simple type of matching commonly
12
associated with shell operations. Advanced
Page 8 of 30
ibm.com/developerWorks
~/tcltk$ tclsh
% set c1 {Bob Carol}
Bob Carol
Lists have two major uses in Tcl. The first we've
% set c2 [list Ted Alice]
already seen demonstrated in the context of
Ted Alice
% set Party1 [list $c1 $c2] processing command line arguments via the
{Bob Carol} {Ted Alice}
foreach command (found on Looping and
% set Party2 [concat $c1 $c2]
branching in Tcl on page 7 ). The second use is to
Bob Carol Ted Alice
% linsert $Party1 1 Richard build up elements of a Tcl command dynamically,
{Bob Carol} Richard {Ted Alice}
which can be later executed by using the eval
%
command, as we see later in this tutorial.
Tcl lists
Page 9 of 30
ibm.com/developerWorks
~/tcltk$ tclsh
% set People(friend) Tom
Tom
% set People(spouse) Marcia The shortcut to understanding Tcl arrays is to
regard them in the same light as you would a Perl
Marcia
% set People(boss) Jack
hash. The array is not a numerically indexed linear
Jack
data structure, unless you choose to impose that
% array names People
interpretation upon your data. The index (or key)
friend boss spouse
% set Person $People(friend) may be any string, although strings with spaces
Tom
need either to be quoted, or a variable reference.
% array get People
friend Tom boss Jack spouse Marcia
Just as with normal variables, arrays are initialized
% set People(friend) \
with the set command, as shown at left. The index
[concat $People(friend) Bob]
Tom Bob
% set Person $People(friend)
Tom Bob
%
Tcl arrays
Page 10 of 30
ibm.com/developerWorks
These array keys are really just the strings "1,10" and "1,11" respectively, but for the
purposes of accessing the data, who's to know the difference?
#!/usr/bin/tclsh
#
# Demonstrate procedures and
The proc command defines a Tcl procedure. Once
# global scoping briefly
set PI [expr 2 * asin(1.0)]
proc circum {rad} {
global PI
return [expr 2.0 * $rad * $PI]
}
proc c_area {rad} {
global PI
return [expr $rad * $rad * $PI]
}
set rad 3
puts stdout "Area of circle of\
radius $rad is [c_area $rad],\n\
the circumference is\
[circum $rad].\n"
*********
~/tcltk$ ./protest.tcl
Area of circle of radius 3 is 28.2743338823,
the circumference is 18.8495559215.
Tcl procedures
Page 11 of 30
ibm.com/developerWorks
#!/usr/bin/tclsh
#
# Demonstrate Data Structures
# using procedural wrappers Beyond simple multi-dimensional arrays, it is
generally
recommended
that Tcl data structures be
proc UserAdd { Acct rName eMail
phone
} {
global uData
implemented as arrays that have dedicated
if {[info exists uData($Acct,rname)]}
{
procedural interfaces.
This design hides specific
return 1
implementation
details
from the user of the
}
structures, while providing the ability to perform
set uData($Acct,rname) $rName
set uData($Acct,email) $eMail
significant error checking capabilities.
set uData($Acct,phone) $phone
return 0
In the example at left, after declaring uData as a
}
Page 12 of 30
ibm.com/developerWorks
~/tcltk$ tclsh
% file exists hello3.tcl
1
File and path operations are a challenging problem
% file executable testit
in a cross-platform environment. Tcl uses UNIX
0
% file pathtype ./hello3.tcl pathnames (separated using the '/' character by
relative
default), as well as the native pathname
% set dir1 home
construction for the host OS. Even when
home
in-program data is constructed properly, it can be
% set dir2 brian
brian
difficult to ensure that user input matches the
% set dir3 tcltk
system requirements. The file join command is
tcltk
used to convert UNIX formats to native pathnames.
% file join /$dir1 dir2 dir3
Other path string commands include file split,
/home/dir2/dir3
dirname, file extension, nativename, pathtype, and
% file delete testit~
%
tail.
Page 13 of 30
ibm.com/developerWorks
~/tcltk$ tclsh
% nslookup orbdesigns.com
Server:
192.168.1.3
The exec command is used to explicitly execute
Address:
192.168.1.3#53
Name:
orbdesigns.com
Address: 64.81.69.163
% set d [date]
Sun Mar 25 13:51:59 PST 2001
% puts stdout $d
% set d [exec date]
Sun Mar 25 13:52:19 PST 2001
% puts stdout $d
Sun Mar 25 13:52:19 PST 2001
******
% if [catch {open foo r} Chan] {
puts stdout "Sorry, Dave...\n"
}
% gets $Chan
One
% gets $Chan
Two
% eof $Chan
0
% close $Chan
%
Page 14 of 30
ibm.com/developerWorks
Page 15 of 30
ibm.com/developerWorks
executed.
Page 16 of 30
ibm.com/developerWorks
Section 4. Tk commands
What's a widget, anyway?
Tk is the graphical Toolkit extension for Tcl. Tk
release versions are coordinated with those of Tcl.
In the panels that follow, we'll review the Tk widget
set, examine some of the configuration options,
and set up some examples to demonstrate the
useful nature of Tk.
It's difficult to convince any PHB (Pointy Haired
Boss) that this section of the tutorial is work
related. After all, it is about widgets, and
conceptually widgets are closely related to
play...but this is work, so let's dig into it. First,
here's the code for a Tk enhanced "Hello, World!"
#!/usr/bin/wish
#
# Hello World, Tk-style
button .hello -text Hello \
-command {puts stdout \
"Hello, World!"}
button .goodbye -text Bye! \
-command {exit}
pack .hello -padx 60 -pady 5
pack .goodbye -padx 60 -pady 5
Tk widgets
There are remarkably few commands used in the creation of Tk widgets. Better than half are
variants of button or text widgets, as you can see in the following list. Several of these items
are demonstrated in the next panel.
* button - a simple widget with over twenty configuration options from anchor and font to
padx and relief.
* canvas - canvas is a widget that can contain not only other widgets, but an assortment
of structured graphics, including circles, lines, and polygons.
* checkbutton - creates a checkbox-style button widget, which is linked to a variable.
* entry - builds a one-line text entry box.
Tcl/Tk quick start
Page 17 of 30
*
*
*
*
*
*
*
*
*
*
*
ibm.com/developerWorks
A Tk demonstration
As an example of some simple Tk code, the listing
below generates the image at left. The code for the
procedure invoked by the OK button and sample
output is shown in the text window of the image.
~/tcltk$ wish
% . configure -width 200 -height 400
% label .header -text "Tk Tutorial Example"
.header
% place .header -x 5 -y 2
% scale .slider -from 1 -to 100 -orient horiz
.slider
% .slider configure -variable SlidVal
% place .slider -x 5 -y 20
% entry .slidbox -width 5 -textvariable SlidVal
.slidbox
% place .slidbox -x 120 -y 38
% radiobutton .one -text "Don't Worry" -variable Mood -val
.one
% radiobutton .two -text "Be Happy" -variable Mood -value
.two
Page 18 of 30
ibm.com/developerWorks
% place .one -x 5 -y 70
% place .two -x 5 -y 90
% text .twindow -width 22 -height 14 -font {clean -14}
.twindow
% place .twindow -x 5 -y 120
% button .ok -command {process_data $SlidVal} -text "OK"
.ok
% button .cancel -command {exit} -text "Cancel" -backgroun
.cancel
% place .ok -x 15 -y 350
% place .cancel -x 120 -y 350
Tk commands, Part 1
There are over 20 Tk commands, that act on, enhance, or complement the Tk widget set.
These include bell, which rings the bell, depending on the configuration of the X Window
system that's running. bind creates an association between a Tcl script and X events; for
example, a specific key-mouse combination action. clipboard is another of the multi-function
Tk commands -- it contains all the code for clearing, loading, and pasting contents to and
from the Tk clipboard (which is distinct from any clipboard features native to either X or the
window manager you're using).
destroy is used to delete a window and all of its children. Used on the '.' (root) window, it
deletes the entire application. event is a powerful tool for generating virtual window events
and inserting them into the processing queue, as though the actual event (a mouse click on a
button, for example) had happened for real. The font command is used to create specified
instances of system fonts. It permits local (to the script) naming of system fonts, attribute
modification of named fonts, and "deletion" of fonts. Type font families at a wish prompt for
a listing of available fonts for use.
Focus is an important concept in the window management arena -- in any given display, only
one window at a time may have the "attention" of the keyboard and mouse. The Tk focus
command is used to give the script control over the display focus, sending it to specified
windows. A complementary function, grab, allows Tk to monopolize the display focus to the
point where events outside the window are reported within the window's environment. This is
useful when you want to force completion of an option prior to any other system activity
taking place.
Tk commands, Part 2
Continuing with our overview of Tk commands, next up is grid, an interface to the Tk window
geometry master. It is used to order widgets in a window in a rows and columns format.
lower (and the complementary command raise) mediate sub-window visibility. A lowered
window obscures none of its overlapping sibling windows; a raised window is brought to the
top. This is used frequently in multi-document display situations. Many of the Tk widgets and
commands work from a common set of standard options. These may be viewed or added to
by the option command.
For putting widgets and sub-windows inside a window, there are two commands, both of
which have already been demonstrated: pack and place. In its simplest use, pack adds one
or more widgets to a window, and unless otherwise instructed, shrinks the window around
Tcl/Tk quick start
Page 19 of 30
ibm.com/developerWorks
those objects as we saw in the Tk Hello example at the beginning of this section. place sets
and displays objects in a parent window, using either relative or absolute measures, for
example, 5 pixels from the left side or halfway (0.5) down the window.
Other commands include selection, an interface to the X object selection toolset; tk, which
provides access to selected parts of the Tk interpreter's internal state; the winfo command for
retrieving data about Tk-managed windows; and wm, an interface to the running window
manager, for setting a multitude of features from the title bar text to all sorts of geometry
specifications and constraints.
The application (a full listing and image is shown on the next panel) reads the configuration
file and parses each non-blank, non-comment line for a button name and its associated
action. While the script would be easier to write by defining three buttons to run explicit
programs, this more general solution allows me to add just about any feature I want by only
adding a single line to ~/.netsetrc.
A drawback of the code is that it isn't tolerant of a badly formatted config file. It expects a
one-word button name followed by a single space followed by the command (with arguments,
if necessary) to be executed on the button press. But then, a configuration file is theoretically
easier to keep in line than unstructured user input.
A sample Tk app
#!/usr/bin/wish
Page 20 of 30
ibm.com/developerWorks
#
# netset.tcl
# 03.26.2001 bilbrey
set ConFile "~/.netsetrc"
if [catch {open $ConFile r} Conf] {
puts stderr "Open $ConFile failed"
return 1
}
# parse config, define buttons
set Bcount 0
while {[gets $Conf Cline] >= 0} {
if {1 == [string match #* $Cline]} continue
if {[string length $Cline] < 4} continue
set Nend [string wordend $Cline 0]
incr Nend -1
set Bname [string range $Cline 0 $Nend]
set Cbeg [expr $Nend + 2]
set Bcomd "exec "
append Bcomd [string range $Cline $Cbeg end]
incr Bcount
set NextBut "button$Bcount"
button .$NextBut -text $Bname -command $Bcomd
}
if {$Bcount == 1} {
puts stderr "No buttons defined"
return 2
}
# display buttons
while {$Bcount >= 1} {
set NextBut "button$Bcount"
pack .$NextBut -padx 10 -pady 10
incr Bcount -1
}
button .exit -text Exit -command {exit}
pack .exit -padx 10 -pady 10
Page 21 of 30
ibm.com/developerWorks
Page 22 of 30
ibm.com/developerWorks
#!../expect -f
# wrapper to make passwd(1) be non-interactive
# username is passed as 1st arg, passwd as 2nd
set password [lindex $argv 1]There are four key commands in Expect (the
spawn passwd [lindex $argv 0]language, with an uppercase 'E'). First is expect
expect "password:"
(the command, little 'e'), which searches for
send "$password\r"
patterns and executes commands if a match is
expect "password:"
made. For each expect command, there can be
send "$password\r"
several groups, each composed of option flags, a
expect eof
Page 23 of 30
ibm.com/developerWorks
#!/usr/local/bin/expect
# Script to enforce a 10 minute break
# every half hour from typing On the left is a script called carpal, yet another
# Written for someone (Uwe Hollerbach)
example from the source Expect distribution.
# with Carpal Tunnel Syndrome.
# If you type for more than 20 minutes
# straight, the script rings the bell
spawn is the Expect command that's used to
# after every character until you take
create a new process. It's appeared in every
# a 10 minute break.
# Author: Don Libes, NIST
# Date: Feb 26, '95
spawn $env(SHELL)
# set start and stop times
set start [clock seconds]
set stop [clock seconds]
# typing and break, in seconds
set typing 1200
set notyping 600
interact -nobuffer -re . {
set now [clock seconds]
if {$now-$stop > $notyping} {
set start [clock seconds]
} elseif {$now-$start > $typing} {
send_user "\007"
}
set stop [clock seconds]
}
Page 24 of 30
ibm.com/developerWorks
Page 25 of 30
ibm.com/developerWorks
Page 26 of 30
ibm.com/developerWorks
Tix
Tix, which stands for Tk Interface eXtension, is an extraordinary GUI and graphics Tcl/Tk
extension. Tix is currently at version 4.0, and provides a set of 43 commands, most of which
are either Mega-widgets or components for building Mega-widgets, along with a few utilities.
Tix's Web site, at http://tix.mne.com/, claims "With Tix, you can forget about the frivolous
details of the TK widgets and concentrate on solving your problems at hand." It's easy to see
the basis of this claim, when you can quickly create useful interfaces with commands like
tixDirList, tixFileSelectDialog, tixPopupMenu, tixScrolledWindow, and many more.
TclX
Extended Tcl, TclX, is really more than just another "extension". In the words of the authors,
"Extended Tcl is oriented towards systems programming tasks and large application
development. TclX provides additional interfaces to the native operating system, as well as
many new programming constructs, text manipulation tools, and debugging capabilities." The
online home of TclX is found at http://www.neosoft.com/TclX/.
Many of TclX's original features have made it into the core Tcl distribution over the last few
years. However, the TclX team has stayed on the ball, adding such features as dynamically
loading libraries and packages, network programming support, procedures that provide
command access to the math functions normally called by expr, and much more.
TclX is included as a package that can be optionally installed with most standard Linux
distributions. Alternatively, it can be compiled from source, in conjunction with Tcl and Tk.
One very nice feature of recent TclX versions is a program called tclhelp, which is a Tcl
and Tk help browser that is very handy to have around for reference. Highly recommended.
Page 27 of 30
ibm.com/developerWorks
implementations. These include OTcl (the MIT Object Tcl), XOTcl, TOS, Tea (a
Java-styled Tcl OO), stooop (Simple Tcl-Only Object Oriented Programming), and
more.
* Along with [incr Widgets] and the other Mega-widget libraries we've already seen, the
Tk Widgets extensions provide a vast array of added GUI functionality, from image and
video handling widgets to notebook and document interface extensions. This is
definitely one of the places to check before you design something for yourself.
* The Miscellaneous extensions category is a complete grab-bag, with a little something
for everyone. From an alpha toolkit for implementing neural networks (LANE), to data
conversion, message digest and crypto packages (Trf and TrfCrypto), to audio play and
record capabilities (Snack).
* Additionally, there are Tcl/Tk extensions explicitly for both the Mac and Windows
implementations. If you work in either of these environments, you owe yourself a visit.
Page 28 of 30
ibm.com/developerWorks
Page 29 of 30
ibm.com/developerWorks
Your feedback
We look forward to getting your feedback on this tutorial and for future directions in providing
up-to-the-minute information about the always-evolving Linux scripting languages. Also, you
are welcome to contact the author directly at [email protected].
Colophon
This tutorial was written entirely in XML, using the developerWorks Toot-O-Matic tutorial
generator. The open source Toot-O-Matic tool is an XSLT stylesheet and several XSLT
extension functions that convert an XML file into a number of HTML pages, a zip file, JPEG
heading graphics, and two PDF files. Our ability to generate multiple text and binary formats
from a single source file illustrates the power and flexibility of XML. (It also saves our
production team a great deal of time and effort.)
You can get the source code for the Toot-O-Matic at
www6.software.ibm.com/dl/devworks/dw-tootomatic-p. The tutorial Building tutorials with the
Toot-O-Matic demonstrates how to use the Toot-O-Matic to create your own tutorials.
developerWorks also hosts a forum devoted to the Toot-O-Matic; it's available at
www-105.ibm.com/developerworks/xml_df.nsf/AllViewTemplate?OpenForm&RestrictToCategory=11.
We'd love to know what you think about the tool.
Page 30 of 30