Tcl/Tk Tutorial
Dongsoo S. Kim
[email protected]
What is Tcl/Tk?
Tcl: Tool Command Language
Interpreted programming (scripting)
language
Build on-the-fly commands and procedures
Embeddable
Platform-independent
Tk:
GUI toolkit and widgets based on Tcl
Open source, cross-platform
Why Tcl/TK?
Easy and fast programming
Free
Lots of online documentation, mostly free
Resources
http://www.tcl.tk
Major applications use the Tcl as their
interfaces:
Ns2
Mentor Graphics
Hello World
% tcl
tcl>puts "Hello. World!"
Hello. World!
tcl>exit
%
Script File
Start the Tcl program followed by a
filename containing the script.
% cat hello.tcl
puts "Hello. World!"
% tcl hello.tcl
Hello. World!
%
Script as a Program
A script text file can be considered as a
program if
it is an executable file, and
its first line contains a full path name of the tcl
program following #!
% ls -l
-rwxr-xr-x
1 user
% which tcl
/usr/local/bin/tcl
% cat hello.tcl
#!/usr/local/bin/tcl
puts "Hello. World!"
% hello.tcl
Hello. World!
%
group
42 Jul
3 13:12 hello.tcl
Tcl Syntax
Simple syntax
command_name arg1 arg2
Print to screen (puts)
puts nonewline "Hello. "
puts "World!"
Assignment (set)
set income 32000
puts "The income is $income"
Use '$' to get the value of a variable (R-value)
Comments
A line started with a pond sign(#) is ignored
as comments until the end of the line
A command can be followed by a comment
in a line with by placing ;#
Exception
#! at the first line indicates the script program
It is a Unix rule, but not a Tcl rule
# the first script
puts nonewline "Hello. "
puts "World!
;# continuing
Multiple Commands in a
Line
A Tcl command is terminated by an
invisible new line character, or
A semicolon(;) can be used to
explicitly terminate a command
tcl>puts "Hello. "; puts "World! "
hello
world
A Command Stretched to Lines
A command can be stretched to
multiple lines by using backslashes (\)
The backslash and a following new line
character is ignored
Note: There must not be any characters
(even space characters) between the
backslash and the new line character
tcl>puts -nonewline \
=>"Hello. World!"
Hello. World!tcl>
10
Mathematical Expression
Mathematical expression command (expr)
Operators
arithmetic (+, -, *, /, %)
Bitwise (~, <<, >>, &, ^, |)
Logical (!, &&, ||)
Boolean (<, >, <=, >=, ==, !=)
String Boolean (eq, ne, <, >, <=, >=)
List containment (in, ni)
Ternary (x?y:z)
Math functions (log, sin, cos, )
Tcl>set pi 3.141592
Tcl>set r 2
Tcl>expr 2*$pi*$r
12.566368
Tcl>expr sin($pi/3)
0.866025294853
11
Sub-Command Evaluation
A Tcl command in a Tcl command: []
tcl>set a 3.0
tcl>set b $a+4
tcl>puts $b
3.0+4
tcl>set c [expr $a+4]
tcl>puts $c
7.0
12
Control Structures (if)
if {cond} {commands}
[ elseif {cond} {commands} ]
[ else {commands} ]
set sel 3
if {$sel
puts
} elseif
puts
} else {
puts
}
== 1} {
"Selection $sel"
{$sel == 2} {
"Selection $sel"
"Invalid selection"
13
Control Structures (while)
while {cond} {commands}
set i 1
set sum 0
while {$i <= 10} {
set sum [expr $sum+$i]
incr i
}
14
Control Structures (for)
for {init} {term} {incr} {statements}
puts "Fahrenheit\tCelcius"
for {set fahr 0} {$fahr < 100} {incr fahr} {
set celc [expr 5*($fahr-32)/9]
puts "$fahr\t\t$celc"
}
Fahrenheit
0
1
2
-17
Celcius
-18
-18
15
Control Structures (foreach)
Basic foreach
set weekdays {Sun Mon Tue Wed Thu Fri Sat}
foreach d $weekdays {
puts $d
}
foreach Variations
set Colors {red orange yellow green blue purple}
foreach {a b c} $Colors {
puts "$c--$b--$a
}
set Foods {apple orange banana lime berry grape}
foreach f $Foods c $Colors {
puts "a $f is usually $c"
}
foreach {a b} $Foods c $Colors {
puts "$a & $b are foods. $c is a color."
}
16
Procedures
Called by value only
Syntax
proc name arg-list proc-body
proc mile2km dist {
return [expr $dist*1.6]
}
puts "Miles \t KM"
for {set d 1} {$d < 10} {incr d} {
set km [mile2km $d]
puts "$d\t $km"
}
17
Variable scope
By default, all variables in a procedure
are local.
To access the variable outside of the
scope,
the command global.
set ause
5
set b 6
set c 7
proc var_scope { } {
global a
set a 3
set b 2
set ::c 1
}
var_scope
puts "The value for a b c is: $a $b $c"
18
Lists in Tcl
An ordered collection of elements
A string containing any number of elements
separated by white spaces (space or tab
characters). For example,
Sun Mon Tue Wed Thu Fri Sat
is a list with four element.
To save a list to a variable
set my_list [list a b c]
set my_list "a b c "
set my_list {a b c}
19
List Operations
concat join multiple list into a single list
join concatenate list elements into a string
lappend append elements to an existing list
lindex return an indexed element from a list
linsert insert an element to an existing list
list create explicitly a list from values
llength return the number of elements in a list
lrange return a sub-list from a list
lreplace return a new list after replacing elements
lsearch return the index of a searching pattern
lsort sort the list
split return a list by splitting a string by a split-char.
20
List Operations, Example
set weekday [list Mon Tue Wed Thu Fri]
set weekend {Sat Sun}
set week [concat $weekday $weekend]
puts $week
Mon Tue Wed Thu Fri Sat Sun
lindex $week 0
Mon
lindex $week end
Sun
llength $weekday
5
21
Lists of lists (of lists)
set a [list [list x y z]]
puts [lindex $a 0]
puts [lindex [lindex $a 0] 1]
puts [lindex [lindex $a 1] 0] (unexpected result)
set a [list x [list [list y] [list z]]]
=> How to get to the z?
set arg1 [list g [list f [list h [list i X]]] [list r Y] k]
set arg2 [list g [list f [list h [list i Y]]] [list r b] L]
set both [list $arg1 $arg2]
puts $both
23
Array operations
Associative arrays (string as index)
set color(rose) red
set color(sky) blue
set color(medal) gold
set color(leaves) green
set color(blackboard) black
puts [array exists color]
(tests if an array with the name "color" exists)
puts [array exists colour]
puts [array names color] (returns a list of the index
strings)
foreach item [array names color] {
puts "$item is $color($item)"
}
(iterating through array)
set lstColor [array get color] (convert array to list)
array set color $lstColor
(convert list to array)
24
Regular expressions
regsub
set stmt "Fan is one of Shanias fans"
regsub nocase "fan" $stmt "Kristy" newStmt
?switches? exp
string
subSpec ?
varName?
puts "$newStmt"
regsub nocase all "fan" $stmt "Kristy" newStmt
puts "$newStmt"
regexp
(returns 1 if the regular expression matches the string,
else returns 0)
puts [regexp nocase "fan" $stmt]
?switches? regexp string
format
puts [format "%s is a %d-year-old" Fan 26]
arg ...?
formatString
?arg
25
String operations
set statement "
Fan is a student
"
set statement [string trim $statement]
puts [string length $statement]
puts [string length statement]
puts [string index $statement 4]
puts [string index $statement end]
puts [string first "is" $statement]
(string last)
puts [string first $statement "is"]
puts [string range $statement 4 end]
puts [string replace $statement 9 end "professor"]
puts [string match "*student" $statement] (* ? [])
26
File Operations
set fRead [open source.txt r]
set fWrite [open target.txt w]
while {![eof $fRead]} {
set strLine [gets $fRead] ;#or gets $fRead strLine
regsub nocase all "fan" $strLine "kristy" strLine
puts $fWrite $strLine
}
close $fRead
close $fWrite
################
source.txt
################
Fan is a CSE student.
Fan is also one of Shanias fans.
Kristy and Fan are classmates.
27
Miscellaneous commands
eval: execute a command dynamically built
up in your program
set Script {
set Number1 17
set Number2 25
set Result [expr $Number1 + $Number2]
}
eval $Script
exec: execute external programs
clock
trace
info
after
28