Sie sind auf Seite 1von 70

Building Applications with Tcl/Tk

Lee Bernhard
Scriptics Corporation
2593 Coast Ave., 2nd Floor
Mountain View, CA 94043
lfb@scriptics.com

A Brief Introduction to Tcl/Tk

Part of a 3-day Course:


Building Applications with Tcl/Tk
3-day Introductory Course

Other Courses
Effective Tcl/Tk Programming
2-day Advanced Topic
Object-Oriented Programming with [incr Tcl]
2-day Advanced Topic
Automated Testing and System Administration with Expect
2-day Advanced Topic

A Brief Introduction to Tcl/Tk

Schedule
Part 1:

Part 2:

What is Tcl/Tk?

Putting Widgets Together

Getting Started

Tapping into Events

The Tcl language

Canvas Widget
Extensions

A Brief Introduction to Tcl/Tk

What is Tcl/Tk?

What is Tcl/Tk?

Tk

(GUI toolkit)

Tcl

(scripting language)

button .b -text "Hello World!" -command exit


pack .b -padx 4 -pady 6

Developed by John Ousterhout at UC Berkeley, now at Scriptics Corporation


Can use, modify and distribute without royalties
More than 500,000 users worldwide

A Brief Introduction to Tcl/Tk

What is Tcl/Tk?

What Can You Build With Tcl/Tk?

Production-quality
graphical user interfaces

Web-based applications:
Servlets (active server pages)
Applets (client-side applications)
CGI scripts

Embedded command language


for controlling complex apps

A Brief Introduction to Tcl/Tk

What is Tcl/Tk?

Cross-Platform Support

UNIX

Windows 95/98/NT

Write one script runs anywhere


Native look and feel
Tcl/Tk version 8.0 and beyond
6

A Brief Introduction to Tcl/Tk

Macintosh

What is Tcl/Tk?

Add-On Packages
Tcl was designed to be extensible
[incr Tcl]

BLT

Tk
Tcl

...

wish
Popular Extensions:
BLT ........................................ plotting, tabnotebook, hierarchical list, and other widgets
[incr Tcl]................................. adds object-oriented support to the Tcl language
Expect ................................... controls command-based tools (legacy programs)
TclX ....................................... lots of extra commands for POSIX functions, looping, etc.
Togl ........................................ OpenGL widget for Tk (3D graphics)
OraTcl / SybTcl...................... interface with Oracle/Sybase databases
Scotty .................................... support for network management applications
Contributed Sources Archive: http://www.neosoft.com/tcl
7

A Brief Introduction to Tcl/Tk

What is Tcl/Tk?

Mission Critical Applications

Source-Navigator
from Cygnus Solutions
http://www.cygnus.com/sn

Mission planner for the


Hubble Space Telescope

Control software for an oil rig in the Gulf of Mexico

A Brief Introduction to Tcl/Tk

What is Tcl/Tk?

Commercial Support
Scriptics Corp. (www.scriptics.com)

TclPro Development Environment


Interactive, graphical debugger
Syntax Checker
Compiler (stores byte code)
Wrapper (builds executables that you can redistribute)

Support Contracts
Consulting
Training

NeoSoft (www.neosoft.com)
Consulting
Training
Many others listed at: www.scriptics.com/resource/commercial

A Brief Introduction to Tcl/Tk

What is Tcl/Tk?

Installing Tcl/Tk
TclPro from Scriptics Corp.

Platforms:
Windows 95/NT, Solaris, HPUX, Linux
SGI IRIX

Tcl Blast! CD-ROM from the Tcl/Tk Consortium

Platforms:

www.scriptics.com

www.linuxcentral.com

Windows 95/NT, Macintosh, Solaris, HPUX,


Linux, SGI IRIX, AIX, Alpha OSF, FreeBSD, SCO
OpenServer, SCO UnixWare7

Download the source code and compile

For details, see: www.scriptics.com/software/8.1.html

10

A Brief Introduction to Tcl/Tk

What is Tcl/Tk?

Other Resources
Scriptics Corp., www.scriptics.com
Start-up company commercializing Tcl/Tk
Web site has:

Tcl/Tk source code, pre-compiled binaries for Windows/Mac,


store for commercial products, resource center

The Tcl/Tk Consortium, www.tclconsortium.org


Non-profit organization supporting the Tcl/Tk development community
Web site has:

books, manual pages, downloads, installation instructions,


companies for consulting/training, etc.

Contributed Sources Archive

www.neosoft.com/tcl
Newsgroups

comp.lang.tcl
comp.lang.tcl.announce
Books

www.scriptics.com/resource/doc/books

11

A Brief Introduction to Tcl/Tk

Schedule
Part 1:

Part 2:

What is Tcl/Tk?

Putting Widgets Together

Getting Started

Tapping into Events

The Tcl language

Canvas Widget
Extensions

12

A Brief Introduction to Tcl/Tk

Getting Started

Programs:
tclsh .... Tcl language shell
wish....... Tcl language shell with Tk widgets

Start them up:


Unix Command Prompt
Tcl Command Prompt
Recognized Tcl commands

Leave tclsh

Recognized Tcl/Tk commands

Leave wish
13

$ tclsh
% info commands
tell open eof pwd glob list pid exec time
unknown eval lrange lsearch gets case lappend
proc break llength auto_execok return linsert
error catch info split array if auto_mkindex
...
% exit

$ wish
% info commands
tell open eof pwd glob list listbox pid exec
pack time unknown eval lrange checkbutton
lsearch gets canvas case lappend proc place
bind break llength return linsert error ...
% exit

A Brief Introduction to Tcl/Tk

Getting Started

Hello World
Main window named "."
created automatically by wish

button .b

Start up wish

$ wish

Make a button

% button .b -text "Hello World!" -command exit


.b

Make it visible on the screen


and pad around button

% pack .b -padx 4 -pady 4

Notes:
All widget names start with ".", e.g.: .b

.b2

.helloWorld

Widget names reflect hierarchy: .gparent.parent.child


All widgets are invisible until packed
14

A Brief Introduction to Tcl/Tk

Getting Started

Tcl Syntax
# comment
command arg arg...
command arg \
arg arg...
command arg arg... ; command arg arg...
command arg arg... ;# inline comment

Examples:
Quotes keep words together
as one argument

button .b -text "Hello World" -command exit


command arg

arg

arg

arg

arg

# -----------------------------# Simple example


# -----------------------------button .b -text "Hello World!" \
-command exit
pack .b
;# make it visible

15

A Brief Introduction to Tcl/Tk

Getting Started

Command Scripts
file: examples/hello.tcl
# --------------------------------------------# EXAMPLE: simple "Hello World!" application
# --------------------------------------------# COURSE: Building Applications with Tcl/Tk
# AUTHOR: Michael J. McLennan
# =============================================
button .b -text "Hello World!" -command exit
pack .b -padx 4 -pady 4

$ wish
% source hello.tcl
% exit
EDIT hello.tcl to say
"Hello Universe!"

$ wish
% source hello.tcl
% button .q -text "Quit"
.q
% pack .q
%

16

Test out ideas


interactively

A Brief Introduction to Tcl/Tk

Getting Started

Widgets are Objects


Create a widget
button .b -text "Hello World!"

Widget name becomes a Tcl command

Access an existing widget


.b configure -command exit
.b flash
.b invoke

Make Button Blink


Push Button Programmatically

Other commands manipulate widgets:


pack .b -padx 4
destroy .b

command .b is destroyed along with widget

17

A Brief Introduction to Tcl/Tk

Getting Started

Configuration Options
% button .b -text "Hello World!"
.b
% pack .b
% .b configure
{-activebackground activeBackground Foreground #ececec #ececec} {-activeforeground
activeForeground Background Black Black} {-anchor anchor Anchor center center} {-background
background Background #d9d9d9 #d9d9d9} {-bd borderWidth} {-bg background} {-bitmap bitmap Bitmap
{} {}} {-borderwidth borderWidth BorderWidth 2 2} {-command command Command {} {}} {-cursor
cursor Cursor {} {}} {-disabledforeground disabledForeground DisabledForeground #a3a3a3
#a3a3a3} {-fg foreground} {-font font Font -Adobe-Helvetica-Bold-R-Normal--*-120-*-*-*-*-*-* Adobe-Helvetica-Bold-R-Normal--*-120-*-*-*-*-*-*} {-foreground foreground Foreground Black
Black} {-height height Height 0 0} {-highlightbackground highlightBackground
HighlightBackground #d9d9d9 #d9d9d9} {-highlightcolor highlightColor HighlightColor Black
Black} {-highlightthickness highlightThickness HighlightThickness 2 2} ...
% .b configure -background
-background background Background #d9d9d9 #d9d9d9
% .b cget -background
#d9d9d9
% .b configure -background green
% .b configure -background blue -foreground white

18

A Brief Introduction to Tcl/Tk

Get info for one option:


switch name
resource name
resource class
initial value
current value

Getting Started

Anatomy of a Tk Widget
file: examples/label.tcl
# ----------------------------------------------------------# EXAMPLE: explore common configuration options
# ----------------------------------------------------------# COURSE: Building Applications with Tcl/Tk
# ===========================================================
label .x -text "Red Alert" -width 12 -height 2 -anchor c \
-borderwidth 2 -relief groove -padx 2 -pady 2
pack .x -padx 10 -pady 10

Start up a wish and explore configuration options:


$ wish
% source label.tcl
% .x configure -background red -foreground white

19

A Brief Introduction to Tcl/Tk

Getting Started

Colors
HINT:
Use these to select
colors:
xcolors
xco
xcoloredit
showrgb

-foreground color
-background color

Color values:
color name........red, tomato, salmon, etc.
RGB value ........#RRGGBB

Try this:
.x configure -background red -foreground white
.x configure -background #00ff00
.x configure -bg tomato -fg black

20

A Brief Introduction to Tcl/Tk

Getting Started

Text

-text string
-justify left/center/right
-wraplength size

Screen Distances:
3 .............3 pixels
5p...........5 points (5 1/72")
4.2i ......4.2 inches
10m.........10 mm
3.1c ......3.1 cm

Try this:
.x
.x
.x
.x

21

configure
configure
configure
configure

-text "Red\nAlert" -justify center


-width 0 -height 0
-text "Really long message that might not fit on one line"
-wraplength 1i

A Brief Introduction to Tcl/Tk

Getting Started

Font
HINT:
Use these to select
fonts:
xfontsel
xlsfonts

-font xFontName
foundry

family

weight slant

set width

Point size (10)

-adobe-helvetica-bold-o-normal--*-140-*-*-*-*-*-*

Try this:
.x configure -font fixed
.x configure -font -*-courier-bold-o-normal--*-140-*
.x configure -font {Helvetica 16 bold}
22

Tcl/Tk 8.0 and beyond

A Brief Introduction to Tcl/Tk

Schedule
Part 1:

Part 2:

What is Tcl/Tk?

Putting Widgets Together

Getting Started

Tapping into Events

The Tcl language

Canvas Widget
Extensions

23

A Brief Introduction to Tcl/Tk

The Tcl Language

Variables
set x "some value"
Assign this value
Variable name
set x

Query the current value

unset x

Destroy this variable

puts "value = $x"

Print out a message:


$x "some value"

Parsing Variable Names:


set new_val0 "testing"
Variable is all alphanumeric or "_"
characters after $

puts "$new_val0!"
puts "$$x"
"$some value"

First $ is left alone, second is expanded

set middle "456"

24

puts "123$middle789"

Looks like variable named "middle789"

puts "123${middle}789"

Use braces to delimit variable name

A Brief Introduction to Tcl/Tk

The Tcl Language

Using "Pointers" in Tcl


set x "some value"
set var "x"
puts "$var = [set $var]"
x
unset $var

One variable contains the name of


another variable

x
some value

This is a common mistake:


set x "some value"
...
set $x "a new value"
"some value"

Creates a variable named "some value"

Other pathological cases:


set "" "this actually works!"
puts "value = ${}"
set set "this works too!"
puts "value = [set set]"

In theory, variable names can be anything!

set "funny variable name" "some value"


puts "value = ${funny variable name}"

25

A Brief Introduction to Tcl/Tk

The Tcl Language

Handling Math
Pythagorean Theorem:
$
%
3
%
4
%

tclsh
set a 3

set b 4

set c [expr sqrt($a*$a + $b*$b)]

c =

a +b

special command for


mathematical expressions

26

In C you might say...

In Tcl you say...

x = x + 1;

set x [expr $x + 1]

x += 2;

incr x 2
set x [expr $x + 2]

y = sin(2*x/(x-1))

set y [expr sin(2*$x/($x-1))]

A Brief Introduction to Tcl/Tk

The Tcl Language

Conditionals and Looping


if {condition} {
body
}

while {condition} {
body
}

if {condition} {
body
} elseif {condition} {
body
} else {
body
}

foreach varName list {


body
}

for {init} {condition} {next} {


body
}

switch value {
val1 { body }
val2 { body }

27

val3 val4 { body }

"-" is like "or"

default { body }

If present, must
be last switch value

break

Break out of loop

continue

Go back to top of loop

A Brief Introduction to Tcl/Tk

The Tcl Language

Printing a Table of Numbers


file: examples/math1.tcl

for {set x 0} {$x < 10} {incr x} {


puts "$x [expr sin($x)] [expr cos($x)]"
}

Try this:
$ cd /usr/local/tcl-tk/course/examples
$ tclsh math1.tcl
0 0.0 1.0
1 0.841471 0.540302
2 0.909297 -0.416147
3 0.14112 -0.989992
4 -0.756802 -0.653644
5 -0.958924 0.283662
6 -0.279415 0.96017
7 0.656987 0.753902
8 0.989358 -0.1455
9 0.412118 -0.91113

28

A Brief Introduction to Tcl/Tk

Loop through 0, 1, ..., 9


and print a table of
sine/cosine values

The Tcl Language

Formatted Output
file: examples/math2.tcl
puts "
x
puts "----------

sin(x)
----------

cos(x)"
----------"

for {set x 0} {$x < 10} {incr x} {


set s [expr sin($x)]
set c [expr cos($x)]
puts [format "%10.3f %10.3f %10.3f" $x $s $c]

fixed-point
number

Try this:
$ tclsh math2.tcl
x
sin(x)
---------- ---------0.000
0.000
1.000
0.841
2.000
0.909
3.000
0.141
4.000
-0.757
...
...

29

Format specifier:
%10.3f

3 digits after
decimal point
cos(x)
---------1.000
0.540
-0.416
-0.990
-0.654
...

A Brief Introduction to Tcl/Tk

10 spaces wide

The Tcl Language

Coding Style: Braces and Spaces


WRONG:

RIGHT:

if {$x > 0} puts "positive"

if {$x > 0} {puts "positive"}


condition

body

Missing space
if {$x > 0}{
puts "positive"
}

if {$x > 0} {
puts "positive"
}
Use braces!

if $x>0 {puts "positive"}

if {$x > 0} {puts "positive"}

if {$x > 0} {
puts "positive"
}
else {
puts "negative"
}

if {$x > 0} {
puts "positive"
} else {
puts "negative"
}

30

Two commands

A Brief Introduction to Tcl/Tk

Schedule
Part 1:

Part 2:

What is Tcl/Tk?

Putting Widgets Together

Getting Started

Tapping into Events

The Tcl language

Canvas Widget
Extensions

31

A Brief Introduction to Tcl/Tk

Putting Widgets Together

Widgets can Interact with Variables


file: examples/incr.tcl
Display the contents
of the "count" variable

set count 0
label .show -textvariable count
pack .show
button .inc -text "Increment" -command "incr count"
pack .inc
button .dec -text "Decrement" -command "incr count -1"
pack .dec

Increment the count variable


by +/- 1

Run this example:


$ cd /usr/local/tcl-tk/course/examples
$ wish incr.tcl
Name of script file

32

A Brief Introduction to Tcl/Tk

Putting Widgets Together

Quoting
Tcl also supports {} quote characters...
puts "Hello World!"
puts {Hello World!}

Both keep spaces together

puts "Hello
World!"

Both handle multi-line strings

puts {Hello
World!}

The difference is important when you have substitutions...


set count 0
puts "total = $count"
total = 0
puts {total = $count}
total = $count

33

Curly braces prevent substitutions

A Brief Introduction to Tcl/Tk

Putting Widgets Together

How wish Registers Widget Commands


file: examples/quoting.tcl
set i 0
button .braces -text "incr with {}" -command {incr i; puts "i = $i"}
pack .braces
button .quotes -text "incr with \"\"" -command "incr i; puts {i = $i}"
pack .quotes

Run this example:


$ cd /usr/local/tcl-tk/course/examples
$ wish quoting.tcl

i
i
i
i

34

=
=
=
=

1
2
0
0

Test out the buttons

A Brief Introduction to Tcl/Tk

Putting Widgets Together

How wish Executes Widget Commands


Event Loop
$ wish quoting.tcl
Click!
file: quoting.tcl

incr i; puts "i = $i"

set i 0
button .braces -text "incr with {}" \
-command {incr i; puts "i = $i"}
pack .braces
button .quotes -text "incr with \"\"" \
-command "incr i; puts {i = $i}"
pack .quotes

Click!

incr i; puts {i = 0}

button .braces ... -command {incr i; puts "i = $i"}


incr i; puts "i = $i"
button .quotes ... -command "incr i; puts {i = $i}"
incr i; puts {i = 0}
35

A Brief Introduction to Tcl/Tk

Putting Widgets Together

Quoting: Rule of Thumb


Q: When do I use " " and when do I need { } ?

Rule of Thumb:
Use " " for text strings
Use { } for code fragments

Example:

$ wish
% set count 0
{ } around code fragment
0
% button .b -text "Increase" -command {incr count; puts "count = $count"}
.b
" " for text strings
% pack .b
" " for text strings

36

A Brief Introduction to Tcl/Tk

Putting Widgets Together

Capturing Command Results


Some commands produce results that you need to capture:
% image create photo -file earth.gif
image1

% label .l -image "image1"


% pack .l

How do you use this in a program?


set imh [image create photo -file earth.gif]

image1
set imh image1

label .l -image $imh


pack .l

37

A Brief Introduction to Tcl/Tk

[...] execute
this string as a
command, and
put the result in
its place

Putting Widgets Together

Hello World, Revisited


file: examples/hello2.tcl
label .im -image [image create photo -file earth.gif]
pack .im
button .b -text "Hello World!" -command exit
pack .b -padx 4 -pady 4

Try it out:
$ cd /usr/local/tcl-tk/course/examples
$ wish hello2.tcl

label .im -image [image create photo -file earth.gif]

image1
label .im -image image1

38

A Brief Introduction to Tcl/Tk

Putting Widgets Together

Checkbuttons
file: examples/checkbutton.tcl
set im1 [image create photo -file loki2.gif]
set im2 [image create photo -file loki.gif]
label .im
pack .im
checkbutton .cb -text "Enlarge" \
-variable imageVal -onvalue $im1 -offvalue $im2 \
-command {.im configure -image $imageVal}
pack .cb -padx 4 -pady 4
.cb select
.cb invoke

39

"on" state:

"image1" imageVal

"off" state:

"image2" imageVal

A Brief Introduction to Tcl/Tk

Putting Widgets Together

When the checkbutton is invoked...


Event Loop
$ wish checkbutton.tcl
Click!

file: checkbutton.tcl

.im configure -image $imageVal

set im1 [image create photo -file loki2.gif]


set im2 [image create photo -file loki.gif]
label .im
pack .im

"image1"
or
"image2"

checkbutton .cb -text "Enlarge" \


-variable imageVal -onvalue $im1 -offvalue $im2 \
-command {.im configure -image $imageVal}
pack .cb -padx 4 -pady 4
.cb select
.cb invoke

checkbutton .cb ... -command {.im configure -image $imageVal}


substitute $imageVal later, when button is pressed

40

A Brief Introduction to Tcl/Tk

Putting Widgets Together

Radiobuttons
file: examples/radiobutton.tcl
set im1 [image create photo -file earth.gif]
set im2 [image create photo -file saturn.gif]
set im3 [image create photo -file loki.gif]
label .im
pack .im
radiobutton .earth -text "Earth" \
-variable imageVal -value $im1 \
-command {.im configure -image $im1}
pack .earth -padx 4
radiobutton .saturn -text "Saturn" \
-variable imageVal -value $im2 \
-command {.im configure -image $im2}
pack .saturn -padx 4
radiobutton .loki -text "Loki" \
-variable imageVal -value $im3 \
-command {.im configure -image $im3}
pack .loki -padx 4
.earth invoke

41

A Brief Introduction to Tcl/Tk

Putting Widgets Together

Text Entries
file: examples/entry.tcl
label .im -image [image create photo -file earth.gif]
pack .im
entry .entry
pack .entry -padx 4 -pady 4
button .load -text "Load Image" -command {
set file [.entry get]
set im1 [image create photo -file $file]
.im configure -image $im1
}
pack .load -padx 4 -pady 4

Try it out:
type in one of: earth.gif, saturn.gif or loki.gif
click on "Load Image"

42

A Brief Introduction to Tcl/Tk

Putting Widgets Together

When the "Load Image" button is pressed...


Event Loop
$ wish entry.tcl
Click!

file: entry.tcl
label .im -image [image create photo -file earth.gif]
pack .im

set file [.entry get]

entry .entry
pack .entry -padx 4 -pady 4
button .load -text "Load Image" -command {
set file [.entry get]
set im1 [image create photo -file $file]
.im configure -image $im1
}
pack .load -padx 4 -pady 4

set im1 [image create photo -file $file]

.im configure -image $im1

button .load -text "Load Image" -command {


set file [.entry get]
set im1 [image create photo -file $file]
.im configure -image $im1
}

43

A Brief Introduction to Tcl/Tk

Putting Widgets Together

Procedures
Instead of writing code in-line like this:
button .load -text "Load Image" -command {
set file [.entry get]
set im1 [image create photo -file $file]
.im configure -image $im1
}
You can define a procedure like this...
Procedure name
Argument list
proc load_image {fileName} {
set im1 [image create photo -file $fileName]
.im configure -image $im1
}
And use it like this...
load_image earth.gif
or
button .earth -command {load_image earth.gif}

44

A Brief Introduction to Tcl/Tk

Putting Widgets Together

Using a Procedure to Load Images


file: examples/proc.tcl
proc load_image {file} {
set imh [.im cget -image]
image delete $imh
set imh [image create photo -file $file]
.im configure -image $imh
}
label .im -image [image create photo -file earth.gif]
pack .im
entry .entry
pack .entry -padx 4 -pady 4
button .load -text "Load Image" -command {load_image [.entry get]}
pack .load -padx 4 -pady 4

45

A Brief Introduction to Tcl/Tk

Putting Widgets Together

Local Scope vs. Global scope


Each procedure has its own local scope for variables:

"global" command
provides access to
variables at the global
scope

set file "earth.gif"


set imh "image12"
set viewer ".im"
.
.
.

These variables are


independent of these

Global
Scope

proc load_image {file} {


global viewer
set imh [$viewer cget -image]
image delete $imh
set imh [image create photo -file $file]
$viewer configure -image $imh
}

Use global variables to:


share data between procedures
keep variables alive between calls
46

A Brief Introduction to Tcl/Tk

Local
Scope

Putting Widgets Together

Listboxes
file: examples/listbox.tcl
proc load_image {file} {
set imh [.im cget -image]
image delete $imh
set imh [image create photo -file $file]
.im configure -image $imh
}
label .im -image [image create photo -file earth.gif]
pack .im
listbox .lbox -width 15 -height 5
pack .lbox -padx 4 -pady 4
.lbox insert 0 earth.gif saturn.gif loki.gif
.lbox selection set 0
button .load -text "Load Image" -command {
set index [.lbox curselection]
load_image [.lbox get $index]
}
pack .load -padx 4 -pady 4

47

A Brief Introduction to Tcl/Tk

Schedule
Part 1:

Part 2:

What is Tcl/Tk?

Putting Widgets Together

Getting Started

Tapping into Events

The Tcl language

Canvas Widget
Extensions

48

A Brief Introduction to Tcl/Tk

Tapping Into Events

X Server
Network

...
X server

...
Window
Manager

Tcl/Tk
Application
button .b -text "Hello World!" \
-command exit
pack .b -padx 4 -pady 4

X server:

Window Manager:

Tcl/Tk Application:

performs drawing operations

adds border to toplevels

draws widgets

sends events to applications

handles iconify/deiconify

responds to events

handles move/resize

49

A Brief Introduction to Tcl/Tk

Tapping Into Events

Widgets Receive Events


click...

...click!

Events Delivered to Button .b:


...
<Enter>
<Motion>
<Motion>
<ButtonPress-1>
<B1-Motion>
<Leave>
<ButtonRelease-1>
...

Lots of Event Types:


ButtonPress / ButtonRelease ........ mouse button pressed/released
Motion ............................................ mouse pointer moved
Enter / Leave ................................. mouse pointer entered/left widget
FocusIn / FocusOut........................ window got/lost keyboard focus
KeyPress / KeyRelease ................. keyboard key was pressed/released
Configure ....................................... window changed size
Destroy .......................................... window was destroyed
Map / Unmap ................................. window appeared/disappeared
Visibility.......................................... window was covered up
50

A Brief Introduction to Tcl/Tk

Tapping Into Events

Requesting Events via the bind command


bind name eventSpec command
Bind to this thing

Tcl command executed


whenever event occurs
<Modifier-Modifier-Type-Detail>
Particular button or keysym

Modfiiers:
Double
Triple

Control
Shift
Lock
Alt
Meta

B1
B2
B3
B4
B5

Type of event:

M1
M2
M3
M4
M5

ButtonPress
KeyPress
Enter
Motion
etc.

Examples:
bind .b <Double-ButtonPress-1> {puts "double-click!"}
bind .b <Control-KeyPress-d> {puts "key: ^D"}
bind .b <B1-Motion> {puts "holding down B1 and moving!"}

51

A Brief Introduction to Tcl/Tk

Tapping Into Events

Example: Listbox
file: examples/listbox2.tcl
...
label .im -image [image create photo -file earth.gif]
pack .im
listbox .lbox -width 15 -height 5
pack .lbox -padx 4 -pady 4
bind .lbox <Double-ButtonPress-1> {
.load flash
.load invoke
}
.lbox insert 0 earth.gif saturn.gif loki.gif
.lbox selection set 0
button .load -text "Load Image" -command {
set index [.lbox curselection]
load_image [.lbox get $index]
}
pack .load -padx 4 -pady 4

52

A Brief Introduction to Tcl/Tk

Tapping Into Events

Accessing Event Details


bind name eventSpec command

Substitutions are made before command is executed:


%W ...................... name of widget receiving event
%x ...................... x-coordinate for event (relative to parent position)
%y ...................... y-coordinate for event (relative to parent position)
%X ...................... x-coordinate for event (on root window)
%Y ...................... y-coordinate for event (on root window)
%K ...................... keysym for keyboard events
%A ...................... ASCII character for keyboard events
%b ...................... button number for button events
%% ...................... replace with single %

Examples:
bind .b <ButtonPress> {puts "button: %b"}
bind .b <B1-Motion> {puts "drag: %x %y"}

53

A Brief Introduction to Tcl/Tk

Tapping Into Events

Event Details in Action

file: examples/bind.tcl
label .value -width 30 -height 3
pack .value
bind .value <Motion> {.value configure -text "Position = %x %y"}
bind .value <KeyPress> {.value configure -text "Key = %K"}

focus .value

focus .value

Assign focus so that


keyboard events are
delivered to this widget
Keyboard

Try this:
% wish bind.tcl
...move mouse around and press various keys...

54

A Brief Introduction to Tcl/Tk

Tapping Into Events

Class Bindings versus Widget Bindings


file: examples/entry2.tcl
bind Entry <FocusIn> {%W configure -background white}
bind Entry <FocusOut> {%W configure -background gray}

label .im -image [image create photo -file earth.gif]


pack .im
entry .entry
pack .entry -padx 4 -pady 4
bind .entry <KeyPress-Return> {
.load flash
.load invoke
}
button .load -text "Load Image" -command {
set file [.entry get]
set im1 [image create photo -file $file]
.im configure -image $im1
}
pack .load -padx 4 -pady 4

55

A Brief Introduction to Tcl/Tk

Bind to class name "Entry"


and all entry widgets are
affected

Schedule
Part 1:

Part 2:

What is Tcl/Tk?

Putting Widgets Together

Getting Started

Tapping into Events

The Tcl language

Canvas Widget
Extensions

56

A Brief Introduction to Tcl/Tk

Canvas Widget

Interactive Displays
You can use the canvas widget to build interactive drawings and maps

57

A Brief Introduction to Tcl/Tk

Canvas Widget

Canvas Items
Add "items" to the canvas to create drawings

continued...

58

A Brief Introduction to Tcl/Tk

Canvas Widget

Canvas Items
continued...

Embed widgets into drawings

59

A Brief Introduction to Tcl/Tk

Canvas Widget

Display List Model


Each canvas keeps a list of the items added to it

Drawn Last

canvas .c
pack .c

Create Items:
set id [.c create oval \
5 5 10 20 -outline black \
-fill yellow]
Manipulate Items:
.c itemconfigure $id -fill red
.c raise $id
.c lower $id
.c move $id 5 -5
.c scale $id 0 0 2 2
.c delete $id
Drawn First

60

A Brief Introduction to Tcl/Tk

Canvas Widget

Searching the Display List


The canvas helps you locate the items within it

Drawn Last

canvas .c
pack .c
...
foreach id [.c find enclosed 20 20 80 110] {
.c itemconfigure $id -fill red
}

Drawn First

61

Other Search Operations:


.c find closest x y
.c find enclosed x0 y0 x1 y1
.c find overlapping x0 y0 x1 y1

A Brief Introduction to Tcl/Tk

Canvas Widget

Simple Sketch Pad


add_point 98 37
add_point 99 42
add_point 97 45

file: examples/canvas1.tcl
canvas .pad
pack .pad
bind .pad <ButtonPress-1> {add_point %x %y}
bind .pad <B1-Motion> {add_point %x %y}
proc add_point {x y} {
.pad create rectangle [expr $x-4] [expr $y-4] \
[expr $x+4] [expr $y+4] -fill blue -outline ""
}

canvas create rectangle x0 y0 x1 y1 options...

62

A Brief Introduction to Tcl/Tk

Canvas Widget

Rubberbanding
file: examples/canvas2.tcl
bind .pad <ButtonPress-3> {select_start %x %y}
bind .pad <B3-Motion> {select_move %x %y}
bind .pad <ButtonRelease-3> {select_end %x %y}
proc select_start {x y} {
global x0 y0
set x0 $x
set y0 $y
}
proc select_move {x y} {
global x0 y0
.pad delete rubberbox
.pad create rectangle $x0 $y0 $x $y -outline black -tags rubberbox
}
proc select_end {x y} {
global x0 y0
"rubberbox" is the
.pad delete rubberbox
symbolic name for the
foreach item [.pad find overlapping $x0 $y0 $x $y] {
selection rectangle
.pad itemconfigure $item -fill red
}
}

63

A Brief Introduction to Tcl/Tk

Schedule
Part 1:

Part 2:

What is Tcl/Tk?

Putting Widgets Together

Getting Started

Tapping into Events

The Tcl language

Canvas Widget
Extensions

64

A Brief Introduction to Tcl/Tk

Extensions

Extensions
Each extension adds new commands
$ tclsh
% info commands
tell subst open eof pwd glob list pid exec time
unknown eval lrange lsearch gets ...

Tcl
vanilla tclsh

$ wish
% info commands
tell subst open eof pwd glob list pid exec time
unknown eval lrange lsearch gets ...
button checkbutton radiobutton pack place ...

Tk
Tcl
vanilla wish
Tk

$ itkwish
% info commands
tell subst open eof pwd glob list pid exec time
unknown eval lrange lsearch gets ...
button checkbutton radiobutton pack place ...
class namespace import delete ...

[incr Tcl]
Tcl

itkwish

Tk

[incr Tcl]
Tcl

bigwish

65

BLT

$ bigwish
% info commands
tell subst open eof pwd glob list pid exec time
unknown eval lrange lsearch gets ...
button checkbutton radiobutton pack place ...
class namespace import delete ...
graph barchart table bgexec ...

A Brief Introduction to Tcl/Tk

Extensions

Popular Extensions: [incr Tcl]


Object-oriented extension to Tcl
Looks a lot like C++
Makes it easier to develop and maintain large Tcl programs
Supports mega-widgets (filebrowsers, combo boxes, etc.)

Data Structures in vanilla Tcl/Tk:

Data Structures in [incr Tcl]:

set
set
set
set
set

class Pile {
private variable
private variable
private variable
private variable
private variable

PileInfo($name-canvas) ""
PileInfo($name-x) 0
PileInfo($name-y) 0
PileInfo($name-drawcmd) $drawCmd
PileInfo($name-cards) $cardlist

canvas ""
x 0
y 0
drawcmd ""
cardlist {}

public method get {} {


return $cardlist
}
public method position {canvas x y}
public method accept {card}
protected method draw {}
}

66

A Brief Introduction to Tcl/Tk

Extensions

Popular Extensions: BLT


Toolkit of useful widgets and extensions
graph............................... graph widget for X-Y plotting
barchart ........................ graph widget for bar charts
table............................... table-based geometry manager
(more intuitive than the pack facility)
htext............................... displays text with embedded widgets
bgexec............................. exec jobs and get their output asynchronously

graph

busy................................. lock up windows with a busy watch cursor


bitmap............................. embed bitmap data in Tcl script files
drag&drop ...................... drag&drop data between applications

barchart
hierbox

67

table

A Brief Introduction to Tcl/Tk

Extensions

Popular Extensions: Expect


Automate tasks normally handled through a tty terminal
Instead of doing this...
ftp ftp.tcltk.com
220-Welcome
220Name: anonymous
Password: ****
ftp>

You can run an "expect" script like this...


script

ftp

expect

Created by Don Libes at NIST


Like Tcl/Tk, can use, modify, and distribute without royalties
Book: Exploring Expect, Don Libes, O'Reilly and Associates, 1995.
More info: http://expect.nist.gov

68

A Brief Introduction to Tcl/Tk

ftp

Extensions

Writing Your Own Extensions


Create a brand-new wish called "mywish" with your own custom extension
Custom extension
Write a command handler
procedure that exchanges string
data with the Tcl interpreter

Tk
Tcl

Register the new command using


Tcl_CreateCommand()

mywish

Other library procedures

Command handler
(C procedure)

Tcl_CreateCommand()

Tcl
strings

69

strings

A Brief Introduction to Tcl/Tk

More Information
John K. Ousterhout,
Tcl and the Tk Toolkit,
Addison-Wesley, 1994
(ISBN 0-201-63337-X)

Mark Harrison, ed.,


Tcl/Tk Tools,
OReilly, 1997
(ISBN 1-56592-218-2)

Brent B. Welch,
Practical Programming in
Tcl and Tk, 2d ed.,
Prentice-Hall, 1997
(ISBN 0-13-616830-2)

Don Libes,
Exploring Expect,
OReilly, 1994
(ISBN 1-56592-090-2)

Mark Harrison,
Michael McLennan,
Effective Tcl/Tk
Programming,
Addison-Wesley, 1997

Eric Johnson,
Graphical Applications
with Tcl and Tk
M&T Books

Training: http://www.scriptics.com/training
Resource Center: http://www.scriptics.com/resource

70

A Brief Introduction to Tcl/Tk

Das könnte Ihnen auch gefallen