Dev:TclTk Tutorial

Jump to: navigation, search


Tcl/Tk Theories

List & Substitution Theory

In Tcl everything is eventually a list. Everything.

A common error with lists is this:

set file "/home/tom/My Pictures/Some Picture.jpg"
button .b -command "open $file"

Then clicking on the button will throw an error. This is because when the command argument is evaluated (before "button .b ..." is called), it is returned like this:

button .b -command {open {/home/tom/My} {Pictures/Some} {Picture.jpg}}

So each space in our path is interpreted as a new argument to open. Yay!

Trying to run:

button .b -command {open $file}

Will also fail, because variables between {} will not be substituted (ie. the open command will try to open a file on disk literally called $file):

The correct way to do this is therefore:

button .b -command [list open $file]

Which will be evaluated to:

button .b -command {open {/home/tom/My Pictures/Some Picture.jpg}}

Magic Keywords


args is a "magic keyword" for procs in Tcl. You can use it to concatenate all trailing arguments to a proc into a single list. Consider this example where you would expect the same result:

proc foo { args } {
   puts ${args}
proc bar { data } {
   puts ${data}

foo hello world
bar hello world

Evaluates to:

hello world
wrong # args: should be "bar data"
    while executing
"bar hello world"
    (file "test.tcl" line 9)

A more "real-world" example using args:

# A drop-in replacement for exec that catches errors.
rename exec exec_tcl

proc exec { args } {
	set exec_str [list exec_tcl]
	foreach arg ${args} {
		lappend exec_str ${arg}
	if {[ catch ${exec_str} result ]} {
		return "EXEC_ERROR: ${result}"
	} else {
		return ${result}

puts [exec uname -n] ;# Executes correctly.
puts [exec uname -X] ;# Throws Error

Command Theory

In the end everything is interpreted as a command. Even built-in statements, like if or for are Tcl commands.

Therefore running this will work:

set cmd [list if [list 5 > 4] [list puts [list Yes 5 is bigger than 4]]]
eval $cmd

$cmd evaluates to:

if {5 > 4} {puts {Yes 5 is bigger than 4}}

Some Useful Links

TclTk Command Manuals

Tcl8.4 Man Page

Tk8.4 Man Page

TkDocs (An Introduction to Building Tk GUI's)

Links Regarding These Theories

Kakaroto's Mail (From Which This Is Derived)

Forum Pages With Useful Info

Personal tools