Sie sind auf Seite 1von 24

Programming Using Tcl/Tk

These slides are based upon

several Tcl/Tk text books

material byDr. Ernest J. Friedman-Hill

What youll need

PCs in the Computer Science Lab have it installed


Start / Tcl / Wish
Start / Widget tour

Or install it on your own computer


Windows & Macintosh: free binaries available
Most Unix: source available

Documentation
books can be bought (bookstore, etc)
books in the PC lab

up-to-date man pages on-line


Start / Help

What is Tcl/Tk?

Tcl
a scripting language
can be extended in C (but this is harder)
ugly but simple

Tk
a simple but powerful widget set
Hello World: a complete program that exits when a person
presses the button

grid [ button .myButton -text "Hello World" -command exit ]

Simple things are simple, hard things are possible

Tcl Language Programming


There are two parts to learning Tcl:
1. Syntax and substitution rules:
Substitutions simple (?), but may be confusing at first.
2. Built-in commands:
Can learn individually as needed.
Control structures are commands, not language syntax.

Scripts and Commands

Tcl script =
Sequence of commands.
Commands separated by newlines, semi-colons.

Tcl command =
One or more words separated by white space.
First word is command name, others are arguments.
Returns string result.

Examples:
set

myName Saul

puts "My Name is $myName


set class CPSC-481; puts -nonewline $class

Arguments

Parser assigns no meaning to arguments (quoting by


default, evaluation is special):
setx4
setyx+10
setz$x+10

x is "4 "
y is "x+10
z is "4+10

Different commands assign different meanings to their


arguments. Type-checking must be done by commands
themselves.
expr24/3

arg is math expresson -> 8


eval"seta122"
evaluate argument as a command
button.btextHellofgredsome args are options (the -)
stringlengthAbracadabra
some args are qualifiers (length)

Variable Substitution

Syntax: $varName

Variable name is letters, digits, underscores.


This is a little white lie, actually.

May occur anywhere in a word.


Sample command

Result

setb66
setab
seta$b
seta$b+$b+$b
seta$b.3
seta$b4

66
b
66
66+66+66
66.3
no such variable

Command Substitution

Syntax: [script]

Evaluate script, substitute result.

May occur anywhere within a word.


Sample command

Result

setb8
seta[expr$b+2]
seta"b3is[expr$b3]"

8
10
b3is5

Controlling Word Structure

Words break at white space and semi-colons, except:


Double-quotes prevent breaks:
seta4;sety5
seta"xis$x;yis$y"
-> xis4;yis5
Curly braces prevent breaks and substitutions:
seta{[expr$b*$c]}
>[expr $b*$c]
Backslashes quote special characters:
setaword\with\\$\and\space
->word with $ and space

Controlling Word Structure


(continued)
Backslashes can escape newline (continuation)
set aLongVariableNameIsUnusual \
This is a string
-> This is a string

Substitutions don't change word structure:


set a "two words"
set b $a
-> two words

Comments

The # is the comment command

Tcl parsing rules apply to comments as well


seta22;setb33<OK
#thisisacomment<OK
seta22#samething?<Wrong!
seta22;#samething<OK

Summary of Tcl Command Syntax

Command: words separated by whitespace

First word is a function, others are arguments

Only functions apply meanings to arguments

Single-pass tokenizing and substitution

$ causes variable interpolation

[ ] causes command interpolation

prevents word breaks

{ } prevents all interpolation

\ escapes special characters

TCL HAS NO GRAMMAR!

Tcl Expressions

Arguments are interpretted as expressions in some


commands: expr, if, ...
Sample command
Result
set b 5
5
expr ($b*4) - 3
17
expr $b <= 2
0
expr {$b * cos(4)}
-3.268
Some Tcl operators work on strings too
(but safer to use the string compare command)
set a Bill
Bill
expr {$a < "Anne"}
0
expr {$a < "Fred"}
1

Tcl Arrays

Tcl arrays are 'associative arrays': index is any string


set foo(fred) 44
set foo(2) [expr $foo(fred) + 6]
array names foo

;# 44
;# 50
;# fred 2

You can 'fake' 2-D arrays:


set A(1,1) 10
set A(1,2) 11
array names A
=>

1,1 1,2

(commas included in names!)

Lists

Zero or more elements separated by white space:


set colors {red green blue}

Braces and backslashes for grouping:


set hierarchy {a b {c d e} f})
set two_item_list {one two\ two}

List-related commands:
concat
lindex
foreach
linsert
lappend
list

llength
lrange
lreplace

lsearch
lsort

Note: all indices start with 0. end means last element

Examples:
lindex {a b {c d e} f} 2
c d e
lsort {red green blue} blue green red

String Manipulation

String manipulation commands:


regexp format

split

string

regsub scan join

string subcommands
compare first
match

range

trimleft

last
toupper

index

length

tolower

trim

trimright

Note: all indexes start with 0. end means last char


string tolower "THIS"
string trimleft XXXXHello
string index abcde 2

;# this
;# Hello
;# c

Control Structures

C-like in appearance.

Just commands that take Tcl scripts as arguments.

Commands:
if
foreach

for
while

switch
eval

break
continue

if else
set x 2
if {$x < 3} {
puts "x is less than 3"
} else {
puts "x is 3 or more"
}

while
#list
set a
set b
set i
while

reversal
{a b c d e}
"
[expr [llength $a] - 1]
{$i >= 0} {
lappend b [lindex $a $i]
incr i -1

}
puts $b

for and foreach


for {set i 0} {$i<10} {incr i} {
puts $I
}
foreach color {red green blue} {
puts I like $color
}
set A(1) a; set A(2) b; set A(26) z
foreach index [array names A] {
puts $A($index)
}

switch
set pete_count

set bob_count

set other_count 0
foreach name {Peter Peteee Bobus Me Bobor Bob} {
switch -regexp $name {
^Pete* {incr pete_count}
^Bob|^Robert {incr bob_count}
default {incr other_count}
}
}
puts "$pete_count $bob_count $other_count"

Procedures

proc command defines a procedure:


proc decrement {x} {
expr $x-1
name
body
}
list of argument names

Procedures behave just like built-in commands:


decrement 3 2

Arguments can have default values:


proc decrement {x {y 1}} {
expr $x-$y
}
decrement 100 5
;# 95
decrement 100
;# 99

Procedures

Procedures can have a variable number of arguments


proc sum args {
set s 0
foreach i $args {
incr s $i
}
return $s
}
sum 1 2 3 4 5
15
sum
0

Procedures and Scope

Scoping: local and global variables.


Interpreter knows variables by their name and scope
Each procedure introduces a new scope

global procedure makes a global variable local


set outside "I'm outside"
set inside

"I'm really outside"

proc whereAmI {inside} {


global outside
puts $outside
puts $inside
}
whereAmI "I wonder where I will be"
-> I'm outside
I wonder where I will be

Das könnte Ihnen auch gefallen