You are on page 1of 39

Introduction to Tcl/Tk

George Whiteman March 31, 2002

1

March 31, 2002

Introduction to Tcl/Tk

Contents
1 Introduction 2 The History of Tcl/Tk 3 Tcl/Tk - Why and Why Not 3.1 Why use Tcl/Tk? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3.2 Why not use Tcl/Tk? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 Interpreter shells 4.1 The tclsh interpreter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4.2 The wish interpreter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 Manpage Support 6 Getting started 6.1 Comments . . . . 6.2 Line Continuation 6.3 Curly Braces . . 6.4 Square Brackets . 6.5 Substitution . . . 6.6 Math Functions . 6.7 Octal Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 6 7 7 8 9 9 10 11 12 12 12 13 13 13 13 14 14 14 15 16 17 18 18 19 19 19 19 20 20 21 21 22 23 24 25 26 26 27 27 28 29 29

7 Data Types and Storage 7.1 Simple Variables . 7.2 Strings . . . . . . . 7.3 Lists . . . . . . . . 7.4 Arrays . . . . . . .

8 Flow Control 8.1 if . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 Loop Control 9.1 for . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9.2 foreach . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9.3 while . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 Modular Design and System Interfacing 10.1 Procedures - proc . . . . . . . . . . . . . . . . . . . . . 10.2 Executing external Tcl code - source . . . . . . . . . . . 10.3 Executing system commands - exec and catch statements 10.4 Command Line Arguments - argc and argv . . . . . . . . 10.5 Determining the Operating System . . . . . . . . . . . . 10.6 Determining the hostname . . . . . . . . . . . . . . . . 10.7 Determining the system time . . . . . . . . . . . . . . . 11 File managenemt and Cross Platform operation 11.1 file join . . . . . . . . . . . . . . . . . . . . 11.2 Reading from a file . . . . . . . . . . . . . . 11.3 Writing to a file . . . . . . . . . . . . . . . . 11.4 fconfigure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

12 Regular Expressions 12.1 regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Page 2

March 31, 2002

Introduction to Tcl/Tk 30 30 30 30 30 31 32 33 34 35 36 37

12.2 regsub . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 Tk Geometry Management 13.1 pack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13.2 grid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13.3 place . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 Tk Widgets 14.1 button 14.2 label . 14.3 entry . 14.4 text . 14.5 menu 14.6 canvas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Page 3

2 Date 2002-03-13 2002-03-29 Comment Initial Draft .1 0.March 31.partial Tcl with limited examples Completed Tcl/Tk examples Page 4 . 2002 Introduction to Tcl/Tk Revision History Revision 0.

March 31.tcl 22 17 32 37 21 12 34 13 28 26 27 27 19 19 24 18 33 12 16 36 23 20 13 29 29 30 21 21 15 35 25 14 19 Definitions EDA IDE OS Tcl Tk tclsh wish Electronic Design Automation Integrated Development Envronment Operating System Tool Command Language Took Kit (specifically the Graphical Tool Kit) The Tcl shell The Tcl/Tk shell Page 5 .tcl string.tcl array.tcl catch.tcl foreach.tcl hostname.tcl button.tcl expr.tcl regexp.tcl file read.tcl fconfigure.tcl source.tcl variable.tcl menu.tcl comment.tcl entry.tcl source err.tcl list.tcl quoting.tcl regsub.tcl text.tcl canvas.tcl line continue.tcl time.tcl proc.tcl os.tcl if problems.tcl for. 2002 Introduction to Tcl/Tk List of Examples ex ex ex ex ex ex ex ex ex ex ex ex ex ex ex ex ex ex ex ex ex ex ex ex ex ex ex ex ex ex ex ex ex arg.tcl file join.tcl file write.tcl while.tcl regexp in.tcl label.

The name Tcl (Tool Command Language) was derived from the intended usage as an embedded command processor. If you are serious about learning the Tcl/Tk scripting language please go purchase the books.rr. The Tk toolkit is born. A summary of the history of Tcl/Tk development follows [6]: early 1980s Tcl grows out of Dr.Tcl/Tk for Real Programmers. Any corrections or suggestions can be set to: whiteman@neo. Gives away a few copies of Tcl to early adopters. major corporations. Christopher Nelson (the manpage on steroids) This white paper is work in progress.Tcl/Tk Programmers Reference. A few short examples were taken verbatim from these books and were hopefully referenced accurately.com The current version can be found in PDF format from: http://home. pitfals. the open source community. 1988 Ousterhout starts work on Tcl and sees complexity of GUIs growing.March 31. 2002 Introduction to Tcl/Tk 1 Introduction This white paper is intended to be an short introduction to the Tcl/Tk scripting language. I would recommend the following books in order: 1 . Expect becomes popular among system administrators. 1989 Ousterhout gives a talk on Tcl during the Berkeley Industrial Liaison Conference. After the USENIX presentation.rr. There are several excellent books listed in the bibliography at the end of this white paper.com/whiteman 2 The History of Tcl/Tk The history of Tcl/Tk while not all that incredibly interesting when viewed on its own is a great example of how the open source movement can and does work. and commercial software developers. and frequently used programming constructs. An attempt was made to include the most important Tcl concepts. Page 6 . Decides to make the Tcl source code freely available on the FTP site at Berkeley. 1990 Ousterhout presented a paper on Tcl at the USENIX Conference. This white paper is not a replacement for these texts.Practical Programming in Tcl/Tk. John Ousterhout work on IC design tools at the University of California at Berkeley. Clif Flynt (a great Tk reference) 3 . Over the span of 20 years a simple modular concept has been developed and improved by academia.neo. concludes that the large graphical systems should be built out of reusable components. Don Libes of the National Institute of Standards and Technology. downloads Tcl and produces Expect. All the while the code has remained free and open sourced. startups. Brent Welch (the Tcl/Tk Bible) 2 .

Windows 55%. 2001 ActiveState improves the open source Tcl core releases ActiveTcl as a complement to their ActivePerl offering. Sun puts a dozen people on the team. which provids a speedup of 10x. communicate with the OS. Brian Lewis builds a bytecode compiler for Tcl scripts. a powerful security model that allows untrusted scripts to be evaluated safely. 1997 Ousterhout and Sarah Daniels leave Sun to form Scriptics (Ajuba). 1998 The Tcl Pro 1. 2002 Introduction to Tcl/Tk 1991 The basic features of Tk became usable. menuing. Cross Platform Development .000/month. This release supports Unicode. catch output. 2000 Tcl/Tk moved to SourceForge.Why and Why Not 3.Tcl can exec other programs.0 development tools ship.March 31. Ousterhout presents a paper on Tk at both the USENIX Conference and the X Conference. Unix 40%. so that Tcl scripts can be evaluated in a Web browser. icons. with little or no modifi- Page 7 .lang. 1992 Tk is impoved with multi-line text widgets and a powerful canvas widget.tcl newsgroup. 1994 Ousterhout leaves Berkeley for Sun Microsystems. Concerns over Tcl becoming a proprietary language are discussed on the comp. thread safety. 1995 Sun FTP site dowloads hit 2000 per week. Tcl/Tk gets ported cross-platform to Windows and the Macintosh by Scott Stanton and Ray Johnson.1 first major open source release. The source code is portable and can be interpreted on Linux. Windows.Tcl/Tk has been ported to most popular operating systems. text windows and a graphical canvas.1 Why use Tcl/Tk? Glue . Tk has suport for buttons. control sockets. Jacob Levy and Laurent Demailly build a Tcl plugin. Tcl now has all the facilities needed for mission-critical enterprise applications. 3 Tcl/Tk . labels. Solaris. 1999 Tcl/Tk 8. Tk usage begins to increase dramatically. and Unicode regular expressions. Today Tcl/Tk downloaded at a rate of +30. scrollbars. Adds support in new Komodo IDE along with Perl and Python. TclPro is open sourced. Applications can communicate with a Web browser. Mac as well as other platforms. Jacob Levy implements Safe-Tcl. Within a month about half of the Sun Tcl team joined Scriptics and begins development of TclPro development tools.

This lead to the development of the object oriented language [incr Tcl]. can be functioning within a in a matter of days. 2002 cation. the application or a prototype of the application.Execution speed may be an issue. Compilers and IDE are available. Page 8 .Although Tcl/Tk has a rich set of string and regular expression functions it is probably not the best choice for string handling. Configuration Files .2 Why not use Tcl/Tk? Speed . make your manager happy.Saying ”tickle” may result in the comment ”me Elmo” in front others. Open Source Code .Many custom tasks may require configuration files.Tcl/Tk is a somewhat verbose language and window management becomes more cumbersome as project complexity grows. Tcl/Tk is an interpreted language by default. 3.Embedded products have a standard language interface. Commercial Tool Support . and hopefully have more personal time.The software is free.Tcl/Tk was designed to be embedded and modular from the start.Open source allows developers to embed the language into a software product. Tcl supports this by sourcing Tcl code to setup variables. Cost . Scripted Execution . String Handling .Since Tcl/Tk is a scripted language the source is visable by default. Alienation . This will impress your customers. Many EDA vendors are shipping cross platform applications with Tcl and the interactive command and scripted interface. Introduction to Tcl/Tk Rapid Prototyping .Depending upon the project’s complexity. Changes can be made within a matter of hours. Tcl/Tk may satisfy the requirements of many production applications.Commercial Debuggers.March 31. however compilers are available. There is no need to generate a specification and a parser for the configuration file. Embedded Design . Feel free to refer to the language as Tee-See-Ell if this happens. Consistancy . Prototyping and development time is minimized. Language . The Tcl/Tk code has several formatting rules.

exe.exe or may contain a version number such as tclsh83. Under Windows this program is named tclsh. 2002 Introduction to Tcl/Tk 4 Interpreter shells 4. Screenshot of tclsh Page 9 . This interpreter does not include support for graphical Tk applications.tcl at the command prompt. Scripts are typically executed by entering tclsh program_name.tcl while in the tclsh interpreter. Scripts can also be executed by entering source program_name.March 31. It is executed by entering tclsh at the command prompt.1 The tclsh interpreter tclsh is the Tcl shell interpreter.

It supports Tcl commands as well as the graphical tool kit (Tk).March 31. The first line of the file should be: #!/usr/bin/tclsh similarly for Tcl/Tk executing under the wish interpreter: #!/usr/bin/wish Page 10 . For this to work the Tcl filename must be referenced with an absolute path or be found in the current search path.exe. Under Windows there is a program named wish.tcl at the command prompt. Scripts can also be executed by entering wish program_name. Tcl applications can also be executed by entering in the filename at the command prompt. Screenshot of wish (default output) Under Unix.2 The wish interpreter wish is the Tcl/Tk interpreter. 2002 Introduction to Tcl/Tk 4. The Tcl file must have execute privileges. It is executed by entering wish at the command prompt.exe or may also contain a version name such as wish83.

If no name or value arguments are supplied. ChannelId identifies the channel for which to set or query an option..? _________________________________________________________________ DESCRIPTION The fconfigure command sets and retrieves options for channels. the command sets each of the named options to the corresponding value. in this case the return value is an empty string. 2002 Introduction to Tcl/Tk 5 Manpage Support The manpage (man) command is supported by the tclsh interpreter. If name is supplied but no value then the command returns the current value of the given option.Set and get options on a channel SYNOPSIS fconfigure channelId fconfigure channelId name fconfigure channelId name value ?name value .. If one or more pairs of name and value are supplied. the command returns a list containing alternat ing option names and values for the channel.March 31. Page 11 . so system manpages may be displayed. It should also be noted that this automatic passing of non Tcl commands to the operating system can be disabled by setting the auto noexec variable. A truncated example man page follows: $ tclsh % man fconfigure fconfigure(n) Tcl Built-In Commands fconfigure(n) _________________________________________________________________ NAME fconfigure . Be aware that command not built into the tclsh interpreter will be passed to the operating system for execution.

0001 0002 0003 0004 0005 0006 0007 0008 0009 0010 0011 0012 0013 0014 0015 0016 #!/usr/bin/tclsh #----------------------------------------------------------# example: ex_comment. # this is a malformed comment (no semicolon) # semicolon is require for EOL commment set dog_years [expr (7 * $real_years)] puts "my dog $dog_name is $real_years" puts "he acts $dog_years old" 6. End of line comments are allowed but a semicolon MUST be placed at the end of the interpreted code on that line.tcl #----------------------------------------------------------# the backslash escapes the new line # dont put a space after it! set members { \ george \ fred \ jeff \ alice \ } puts $members Page 12 .1 Comments Comments are line based in Tcl. 2002 Introduction to Tcl/Tk 6 Getting started 6. 0001 0002 0003 0004 0005 0006 0007 0008 0009 0010 0011 0012 0013 0014 0015 #!/usr/bin/tclsh #----------------------------------------------------------# example: ex_line_continue. Do not follow the backslash with any characters. or even any whitespace characters! The backslash escapes the next character which is intended to be the newline.March 31.2 Line Continuation Line continuation is accomplished by using a backslash.tcl #----------------------------------------------------------# tcl is line comment based # no need to use semicolons for line terminations # but they are allowed set real_years 4 set dog_name "spot".

no output.March 31. Curly braces will not allow substitution.5 Substitution Double quotes will allow substitution in the string being quoted. this will cause brace mismatches that can be difficult to find. 0001 0002 0003 0004 0005 0006 0007 0008 0009 0010 0011 #!/usr/bin/tclsh #----------------------------------------------------------# example: ex_expr.tcl #----------------------------------------------------------set years 41 set years_sub "I am $years". 6.3 Curly Braces Curly braces around a string do not allow variable substitution within the string. 0001 0002 0003 0004 0005 0006 0007 0008 0009 0010 0011 0012 0013 #!/usr/bin/tclsh #----------------------------------------------------------# example: ex_quoting. no warnings.0 set pi [expr { 4 * atan(1. set years_no_sub {I am $years}. 2002 Introduction to Tcl/Tk 6. 6. Unmatched curly braces may cause the interpreter to wait indefinitely for more input.4 Square Brackets Square brackets are used for controlling the order of execution. Curly braces count even if they are in a comment. no errors. the string is taken literally.6 Math Functions The interpreter is told to perform math functions by using the expr command.tcl #----------------------------------------------------------set r 2.weak quoting" puts $years_sub puts "this string did not substitute . puts "this string got substituted .rigid quoting" puts $years_no_sub 6.0) }] set area [expr {$pi * $r * $r}] puts "r: $r" puts "pi: $pi" puts "area: $area" Page 13 .

The leading zero may cause problems with the Tcl interpreter.0 set three 3 set threefourths [expr $three / $four] puts "threefourths: $threefourths" set threefourths_real [expr $three / $four_real] puts "threefourths_real: $threefourths_real" Global variables are declared in procedures.1 Simple Variables Variables are initialized with the set command. Non-global variables within a procedure are local to the procedure. This is typically encountered when setting permission modes during the opening a file for writing. like 0644.7 Octal Numbers Numbers with a leading zero. Variables are set without a dollar sign preceeding the variable name. A digit that is greater than or equal to 8 preceeded by a leading zero digit will cause an illegal octal number error. Variables with leading zeros are assumed to be in an octal format. 0001 0002 0003 0004 0005 0006 0007 0008 0009 0010 0011 0012 0013 #!/usr/bin/tclsh #----------------------------------------------------------# example: ex_variable.tcl #----------------------------------------------------------set four 4 set four_real 4. Initialization with an integer (no decimal) or a real value (decimal) will produce different results. 7 Data Types and Storage 7. This is in contrast to other scripting languages like Perl that uses dollar signs for both initialization and referencing. are interpreted as octal. 2002 Introduction to Tcl/Tk 6. Variable are typeless strings but it is important how they are initialized. Variables are referenced with a dollar sign preceeding the variable name.March 31. Page 14 . when doing comparisons or assigments on numbers representing time of day. not up front. The info command can be used to determine if a variable exists or not.

or non-default characters. See the respective manpages a more detailed description. else returns -1 returns the length of str returns 1 if str matches pattern returns substring of str from start to end returns a str repeated n times returns a lowercased str returns str with the first letter capitalized returns a uppercased str trims whitespace from str trims whitespace from the end of str trims whitespace from the beginning of str Many of these string commands have additional options such as nocase.March 31. An example using the string command syntax follows: 0001 0002 0003 0004 0005 0006 0007 0008 0009 0010 0011 #!/usr/bin/tclsh #----------------------------------------------------------# example: ex_string.tcl #----------------------------------------------------------set str1 "th" set str2 "Is this supposed to be a good thing. The table below is not an exhaustive list but it does contain the most commonly used string commands. 0 or 1 test equality of string and returns 1 if equal returns the index of the first occurrence of str2 in str1.2 Strings There is a rich set of string processing commands in Tcl. else returns -1 returns the index of the last occurrence of str2 in str1. Miri?" puts puts puts puts "length: "first: "last: "toupper: [string [string [string [string bytelength $str2]" first $str1 $str2]" last $str1 $str2]" toupper $str2]" Page 15 . Tcl/Tk String Command Summary[1] Command string bytelength str string compare str1 str2 string equal str1 str2 string first str1 str2 string last str1 str2 string length str string match pattern str string range str start end string repeat str n string tolower str string totitle str string toupper str string trim str string trimleft str string trimright str Description returns number of bytes used in for string storage compares string and returns -1. positions. 2002 Introduction to Tcl/Tk 7.

2002 Introduction to Tcl/Tk 7.3 Lists Lists are a sequence of values separated by whitespace.. lreplace list n m arg1 arg2 . An example using the list command syntax follows: 0001 0002 0003 0004 0005 0006 0007 0008 0009 0010 0011 0012 0013 0014 0015 #!/usr/bin/tclsh #----------------------------------------------------------# example: ex_list. lindex list n llength list lrange list n m lappend list arg1 arg2 ..March 31. Braces are typically used to group items together into a single value in a list...tcl #----------------------------------------------------------set the_list { {Red Hat} SuSE Mandrake Debian } puts "value 0: [lindex $the_list 0]" puts "value 1: [lindex $the_list 1]" puts "value 2: [lindex $the_list 2]" puts "value 3: [lindex $the_list 3]" set the_sorted_list [lsort $the_list] puts "value 0: [lindex $the_sorted_list puts "value 1: [lindex $the_sorted_list puts "value 2: [lindex $the_sorted_list puts "value 3: [lindex $the_sorted_list 0]" 1]" 2]" 3]" Page 16 . Tcl lists are strings with a corresponding set of data manipulation commands... lsearch list value lsort list Description constructs a list out of several arguments returns the indexed element from the list returns the number of elements in a list returns the range of elements of a list appends elements to a list inserts elements to a list and returns a new list replaces elements n thru m with args and returns a new list return index of value in list. A incomplete summary of these commands are listed below. else -1 returns a sorted list Many of these list commands also have additional options... Tcl/Tk List Command Summary[1] Command list arg1 arg2 . linsert list index arg1 arg2 . Lists are not used to build complex data structures.

If the index is numeric the array syntax appears similar to other languages that do not use associative arrays. However.rr. The array index to the associative array is placed within parenthesis.tcl #----------------------------------------------------------proc P_add_contact { key last_name email phone } { global contact_last_name global contact_email global contact_phone set contact_last_name($key) set contact_email($key) set contact_phone($key) puts puts puts puts "key: "name: "email: "phone: $last_name $email $phone $key" $contact_last_name($key)" $contact_email($key)" $contact_phone($key)" return } P_add_contact 1000 whiteman whiteman@neo.com 555-555-5557 Page 17 . the indexes need not be numeric.4 Arrays Arrays in Tcl are associative.March 31. meaning that they are stored using a hash table.com 555-555-5556 P_add_contact alphakey ren ren@ren. 2002 Introduction to Tcl/Tk 7.com 555-555-5555 P_add_contact 1001 stimpy stimpy@stimpy. 0001 0002 0003 0004 0005 0006 0007 0008 0009 0010 0011 0012 0013 0014 0015 0016 0017 0018 0019 0020 0021 0022 0023 0024 #!/usr/bin/tclsh #----------------------------------------------------------# example: ex_array.

tcl #----------------------------------------------------------set a 1 # the if statement commented out causes a curly bracket mismatch # if {$a == 1} { if {$a == 0} { puts "a is zero" } else { puts "a is not zero" } # need if {$a puts } else puts } # else if {$a puts } else { puts } space between curly brackets == 0}{ "a is zero" { "a is not zero" is misplaced == 0} { "a is zero" "a is not zero" # formatted properly if {$a == 0} { puts "a is zero" } else { puts "a is not zero" } # this is also formatted properly if {$a == 0} { puts "a is zero" } else { puts "a is not zero" } Page 18 . This is related to how the parser works. 0001 0002 0003 0004 0005 0006 0007 0008 0009 0010 0011 0012 0013 0014 0015 0016 0017 0018 0019 0020 0021 0022 0023 0024 0025 0026 0027 0028 0029 0030 0031 0032 0033 0034 0035 0036 0037 0038 0039 0040 0041 0042 #!/usr/bin/tclsh #----------------------------------------------------------# example: ex_if_problems. 2002 Introduction to Tcl/Tk 8 Flow Control 8.1 if Tcl is quite picky about the format of the if conditional statement.March 31. An example has been included to better illustrate the formatting of this conditional statement.

March 31.tcl #----------------------------------------------------------set random_int 0 while { 1 } { # loop exit condition if { $random_int == 1 } { break } # loop processing set random_float [expr (10 * rand())] set random_int [expr (int($random_float))] puts $random_int } Page 19 .tcl #----------------------------------------------------------set member_list { george 41 alice 37 fred 30 sally 34 dustin 23 } foreach {name age} $member_list { puts [format "name: %-20s age: %3d" $name $age] } 9.1 for 0001 0002 0003 0004 0005 0006 0007 #!/usr/bin/tclsh #----------------------------------------------------------# example: ex_for. 2002 Introduction to Tcl/Tk 9 Loop Control The syntax for loop control is covered in the next three examples. 9.3 while 0001 0002 0003 0004 0005 0006 0007 0008 0009 0010 0011 0012 0013 0014 0015 0016 #!/usr/bin/tclsh #----------------------------------------------------------# example: ex_while.tcl #----------------------------------------------------------for { set loopcnt 0 } { $loopcnt < 10 } { incr loopcnt } { puts "loopcnt: $loopcnt" } 9.2 foreach 0001 0002 0003 0004 0005 0006 0007 0008 0009 0010 0011 0012 0013 0014 0015 #!/usr/bin/tclsh #----------------------------------------------------------# example: ex_foreach.

proc Procedures must be declared before they are referenced. In a script containing many procedures main program execution may be located at the bottom of the file. 2002 Introduction to Tcl/Tk 10 Modular Design and System Interfacing 10. Procedure names may overwrite built in commands.0 set temp [P_procedure1] P_procedure2 $temp Page 20 . Procedures may contain optional pass variables and may also specify defaults for these variables. By defining an exit procedure the normal built in exit command will be modified. This is not recommended practice and some developers use naming conventions to avoid problems.1 Procedures . 0001 0002 0003 0004 0005 0006 0007 0008 0009 0010 0011 0012 0013 0014 0015 0016 0017 0018 0019 0020 0021 0022 0023 0024 0025 0026 0027 0028 0029 0030 0031 0032 0033 0034 0035 0036 0037 0038 0039 0040 #!/usr/bin/tclsh #----------------------------------------------------------# example: ex_proc.0 set variable2 2.March 31.tcl #----------------------------------------------------------#----------------------------------------------------------# procedure 1 #----------------------------------------------------------proc P_procedure1 { } { global variable1 global variable2 puts "variable1: $variable1" puts "variable2: $variable2" set variable3 [expr ($variable1 + $variable2) ] return $variable3 } #----------------------------------------------------------# procedure 2 #----------------------------------------------------------proc P_procedure2 { variable3 } { global variable1 global variable2 puts "variable3: $variable3" return } #----------------------------------------------------------# call the procedures #----------------------------------------------------------set variable1 1.

The following example shows the exec command used with the catch command. 0001 0002 0003 0004 0005 0006 0007 0008 0009 #!/usr/bin/tclsh #----------------------------------------------------------# example: ex_source.tcl #----------------------------------------------------------source ex_source_err. These procedures determine the operating system and hostname of the machine running the script. environment data.exec and catch System calls are performed by the exec command.source Scripts can be subdivided into seperate sections by use of the source statement. Sourcing other Tcl scripts from a main Tcl script provides a way to separate shared procedures. This provides similar functionality to the ”require” in Perl or ”include” in the C language.tcl P_msg_info P_msg_warn P_msg_err "We can Tcl code common to several modules" "This is a warning message" "This is an error message" Below is a listing of the Tcl code that was contained in a different file and sourced. configuration data. 0001 0002 0003 0004 0005 0006 0007 0008 0009 0010 0011 0012 0013 0014 0015 #!/usr/bin/tclsh #----------------------------------------------------------# example: ex_source_err. This is useful for running a system command and capturing the output from that command. 0001 0002 0003 0004 0005 0006 0007 0008 #!/usr/bin/tclsh #----------------------------------------------------------# example: ex_catch.2 Executing external Tcl code . 2002 Introduction to Tcl/Tk 10.tcl #----------------------------------------------------------set system_cmd "ls" set system_arg "-la" catch { exec $system_cmd $system_arg } ls_data puts $ls_data Page 21 . The return values of these procedures can be used to make system and hostname dependent decisions allowing the same code to run on different platforms and hosts. and system dependent data.March 31.tcl #----------------------------------------------------------proc P_msg_info { msg } { puts "INFO: $msg" } proc P_msg_warn { msg } { puts "WARN: $msg" } proc P_msg_err { msg } { puts "ERR: $msg" } 10.3 Executing system commands .

tcl #----------------------------------------------------------proc P_ex_arg { v0 v1 v2 } { puts "v0: $v0" puts "v1: $v1" puts "v2: $v2" return } # check for the proper number of command line arguments if { $argc == 3 } { # print out the script name puts "executing $argv0." # setup the command line arguments set arg1 [lindex $argv 0] set arg2 [lindex $argv 1] set arg3 [lindex $argv 2] # call the main routine P_ex_arg $arg1 $arg2 $arg3 exit 0 } else { # put out an error message puts "usage is: ex_arg.March 31. 0001 0002 0003 0004 0005 0006 0007 0008 0009 0010 0011 0012 0013 0014 0015 0016 0017 0018 0019 0020 0021 0022 0023 0024 0025 0026 0027 0028 #!/usr/bin/tclsh #----------------------------------------------------------# example: ex_arg.4 Command Line Arguments .tcl arg1 arg2 arg3" # set exit status exit 1 } Page 22 . 2002 Introduction to Tcl/Tk 10...argc and argv As with many other languages Tcl can be passed arguments from the command line at the start of command execution.

tcl #----------------------------------------------------------#----------------------------------------------------------# determines operating system #----------------------------------------------------------proc P_determine_os { } { # set the subroutine name set sub_name {P_determine_os} # give the user some information puts "($sub_name) INFO: determining operating system" # execute the system command and catch the output catch { exec uname -sr } uname_return_data # tell the user what uname returned puts "($sub_name) INFO: uname -sr returned: $uname_return_data" # format the output of uname if { [string first "Linux" $uname_return_data] == 0 } { set os_type linux } elseif { [string first "CYGWIN_NT" $uname_return_data] == 0 } { set os_type cygwin } elseif { [string first "SunOS" $uname_return_data] == 0 } { set os_type solaris } else { set os_type undefined } puts "($sub_name) INFO: os_type set to: $os_type" return $os_type } #----------------------------------------------------------# determine operating system using a system call #----------------------------------------------------------P_determine_os exit Page 23 .March 31.5 Determining the Operating System 0001 0002 0003 0004 0005 0006 0007 0008 0009 0010 0011 0012 0013 0014 0015 0016 0017 0018 0019 0020 0021 0022 0023 0024 0025 0026 0027 0028 0029 0030 0031 0032 0033 0034 0035 0036 0037 0038 0039 0040 0041 0042 #!/usr/bin/tclsh #----------------------------------------------------------# example: ex_os. 2002 Introduction to Tcl/Tk 10.

2002 Introduction to Tcl/Tk 10.tcl #----------------------------------------------------------#----------------------------------------------------------# determines hostname #----------------------------------------------------------proc P_determine_hostname { } { # set the subroutine name set sub_name {P_determine_hostname} # give the user some information puts "($sub_name) INFO: determining hostname" # do the system call catch { exec hostname } hostname_return_data # tell the user what uname returned puts "($sub_name) INFO: hostname returned: $hostname_return_data" # no translation set hostname $hostname_return_data # trim the hostname set hostname [string trim $hostname] # lowercase the hostname set hostname [string tolower $hostname] puts "($sub_name) INFO: hostname set to: $hostname" return $hostname } #----------------------------------------------------------# determine the hostname using a system call #----------------------------------------------------------P_determine_hostname exit Page 24 .6 Determining the hostname 0001 0002 0003 0004 0005 0006 0007 0008 0009 0010 0011 0012 0013 0014 0015 0016 0017 0018 0019 0020 0021 0022 0023 0024 0025 0026 0027 0028 0029 0030 0031 0032 0033 0034 0035 0036 0037 0038 0039 0040 #!/usr/bin/tclsh #----------------------------------------------------------# example: ex_hostname.March 31.

tcl #----------------------------------------------------------#----------------------------------------------------------# sets the current_date and current_time global variables #----------------------------------------------------------proc P_set_time { } { global current_date global current_time # set the subroutine name set sub_name {P_set_time} # format time as YYYYMMDD set current_date [clock format [clock seconds] -format "%Y%m%d"] # format the time as HHMM set current_time [clock format [clock seconds] -format "%H%M"] # give the user some information puts "($sub_name) INFO: current date: $current_date" puts "($sub_name) INFO: current time: $current_time" return } #----------------------------------------------------------# call the P_set_time procedure #----------------------------------------------------------P_set_time exit Page 25 .March 31.7 Determining the system time 0001 0002 0003 0004 0005 0006 0007 0008 0009 0010 0011 0012 0013 0014 0015 0016 0017 0018 0019 0020 0021 0022 0023 0024 0025 0026 0027 0028 0029 0030 0031 0032 #!/usr/bin/tclsh #----------------------------------------------------------# example: ex_time. 2002 Introduction to Tcl/Tk 10.

tcl #----------------------------------------------------------#----------------------------------------------------------# produces a text file #----------------------------------------------------------proc P_create_file { } { # set the subroutine name set sub_name "P_create_file" # build up the file name set abs_file_name [file join set abs_file_name [file join set abs_file_name [file join set abs_file_name [file join "/home" "gwhitema"] $abs_file_name "tcl"] $abs_file_name "training"] $abs_file_name "ex_file_join. backslash.1 file join One of the benefits of Tcl and Tk is its ability to execute cross platform. colon) and file formats (cr-lf combinations) have always been problematic to programmers.March 31. File pathnames (slash.txt"] # tell the user what is happening puts "($sub_name) INFO: creating file: $abs_file_name" # open the html file set file_id [open $abs_file_name w 0644] # write some text to the file puts $file_id "this is some text" # close the file close $file_id return } #----------------------------------------------------------# call the P_create_file #----------------------------------------------------------P_create_file exit Page 26 . Tcl solves this problem by building up pathnames using the file join command. 0001 0002 0003 0004 0005 0006 0007 0008 0009 0010 0011 0012 0013 0014 0015 0016 0017 0018 0019 0020 0021 0022 0023 0024 0025 0026 0027 0028 0029 0030 0031 0032 0033 0034 0035 0036 0037 0038 #!/usr/bin/tclsh #----------------------------------------------------------# example: ex_file_join. 2002 Introduction to Tcl/Tk 11 File managenemt and Cross Platform operation 11.

March 31. 0001 0002 0003 0004 0005 0006 0007 0008 0009 0010 0011 0012 0013 0014 0015 0016 0017 0018 0019 0020 0021 0022 0023 0024 0025 #!/usr/bin/tclsh #----------------------------------------------------------# example: ex_file_read. 0001 0002 0003 0004 0005 0006 0007 0008 0009 0010 0011 0012 0013 0014 0015 0016 #!/usr/bin/tclsh #----------------------------------------------------------# example: ex_file_write. The following examples details how to open a file for writing.txt" exit 11. 2002 Introduction to Tcl/Tk 11.tcl #----------------------------------------------------------proc P_read_file { file_name } { # open the file set file_id [open $file_name r] # read in the file line by line foreach line [split [read $file_id] \n] { # process the line puts $line } # close the file close $file_id return } #----------------------------------------------------------# example: example_file_read. The following example details how to open a file for reading and split the data in the file on the new line.tcl #----------------------------------------------------------set file_name "ex_file_write.2 Reading from a file Reading data from a file line by line is a common task in programming.txt" # open the dst file for write set file_id [ open $file_name w 0644 ] # put some data in the file for { set loopcnt 0 } { $loopcnt < 10 } { incr loopcnt } { puts $file_id "loopcnt: $loopcnt" } # close the file close $file_id Page 27 .3 Writing to a file Writing data to a file is also a common programming task. Notice the leading zero in the octal file permission data field when the file is initially opened.tcl #----------------------------------------------------------P_read_file "ex_file_read.

4 fconfigure Tcl can also produce file formats targetted for one OS while executing on a different OS.txt"] # tell the user what is happening puts "($sub_name) INFO: creating file: $abs_file_name" # open the file set file_id [open $abs_file_name w 0644] # generate using unix line terminations # fconfigure $file_id -translation lf # generate using dos line terminations fconfigure $file_id -translation crlf # generate using mac line terminations # fconfigure $file_id -translation cr # write some text to the file puts $file_id "this is line 1" puts $file_id "this is line 2" puts $file_id "this is line 3" # close the file close $file_id return } #----------------------------------------------------------# call the P_create_file_fconfigure procedure #----------------------------------------------------------P_create_file_fconfigure exit Page 28 .March 31. This is accomplished by usign the fconfigure command.tcl #----------------------------------------------------------#----------------------------------------------------------# produces a text file #----------------------------------------------------------proc P_create_file_fconfigure { } { # set the subroutine name set sub_name "P_create_file_fconfigure" # build up the file name set abs_file_name [file join set abs_file_name [file join set abs_file_name [file join set abs_file_name [file join "/home" "gwhitema"] $abs_file_name "tcl"] $abs_file_name "training"] $abs_file_name "ex_fconfigure. 2002 Introduction to Tcl/Tk 11. 0001 0002 0003 0004 0005 0006 0007 0008 0009 0010 0011 0012 0013 0014 0015 0016 0017 0018 0019 0020 0021 0022 0023 0024 0025 0026 0027 0028 0029 0030 0031 0032 0033 0034 0035 0036 0037 0038 0039 0040 0041 0042 0043 0044 0045 0046 0047 0048 0049 #!/usr/bin/tclsh #----------------------------------------------------------# example: ex_fconfigure.

0001 0002 0003 0004 0005 0006 0007 0008 0009 0010 0011 0012 0013 0014 0015 0016 0017 0018 0019 0020 #!/usr/bin/tclsh #----------------------------------------------------------# example: ex_regexp. 2002 Introduction to Tcl/Tk 12 Regular Expressions 12. 0001 0002 0003 0004 0005 0006 0007 0008 0009 0010 0011 0012 0013 #----------------------------------------------------------# example: ex_regexp_in. The following example reads in a file and strips comments indicated by a # sign in the first column.txt #----------------------------------------------------------# this is comment 1 cmd1 # this is comment 2 cmd2 arg1 arg2 # this is comment 3 cmd3 arg1 arg2 arg3 # this is comment 4 cmd4 # this is comment 5 cmd5 Page 29 .March 31.tcl #----------------------------------------------------------# setup the filename set file_name ex_regexp_in.1 regexp Regular expressions are supported through the use of the regexp statement.txt # open the file for reading set file_id [open $file_name r] # read in the file line by line foreach line [split [read $file_id] \n] { # process the line if { [regexp "(ˆ#)" $line match] == 0 } { puts $line } } # close the file close $file_id This is the file used as input to the regexp example above.

March 31. Although this geometry management has limitations during resizing it is most commonly used with text or canvas widgets combined with x and y scrollbars. 0001 0002 0003 0004 0005 0006 0007 0008 0009 0010 0011 0012 0013 0014 0015 0016 0017 0018 0019 0020 0021 0022 0023 0024 #!/usr/bin/tclsh #----------------------------------------------------------# example: ex_regsub.3 place The place geometry manager allows for exact control over the placement of widgets.txt" # set up the dst filename set dst_file_name "output. Page 30 . 13.1 pack The pack geometry manager is the most commonly used.txt" # open the src file for read set src_file_id [ open $src_file_name ] # open the dst file for write set dst_file_id [ open $dst_file_name w ] # read the src line by line while {[gets $src_file_id line] >= 0} { # put your from-to translation strings here puts $dst_file_id [regsub -all {cool} $line {dorky} line] } # close both files close $src_file_id close $dst_file_id 13 Tk Geometry Management Tk controls the construction of widgets using one or more geometry managers. Various combinations of geometry managers can be used within a single Tcl/Tk script.2 regsub String subsititutions are supported through the use of the regsub statement.tcl #----------------------------------------------------------# set up the src filename set src_file_name "input. 13. 2002 Introduction to Tcl/Tk 12. Geometry managers control the resizing and location of widgets during script execution. It operates by packing widgets within hierarchical frames.2 grid The grid geometry management allows for placement on a xy grid consisting of rows and columns. 13.

1 of n can be selected creates a set of buttons. any number can be selected used for a single text input line creates a message text window typically used for labelling other widgets with read only text slider control that calls a routine when the slider position changes displays a scrolldown menu holds menu pulldown items creates a list box that can be scrolled creates a scrollbar that is used to control other widgets creates a frame to control the grouping of other widgets creates a top level window with controls from the window manager creates a text window that can be edited creates a graphic window that is used for drawing and image display Page 31 . This is not a complete table nor does it contain the file dialog widgets available for use. 2002 Introduction to Tcl/Tk 14 Tk Widgets The following table lists the basic types of widgets used by Tk.March 31. Basic Tk Widget Summary[3] Widget button radiobutton checkbutton entry message label scale menubutton menu listbox scrollbar frame toplevel text canvas Description creates a button to execute a command creates a set of buttons.

c2.b0 -side top pack .b1 -side top 0" } 1" } 2" } 3" } 5" } -fill -fill -fill -fill -fill -fill both both both both both both -expand -expand -expand -expand -expand -expand true true true true true true # pack the column frames pack .c1 frame .c0.c2.c0.c0.b1 -side top pack .c2 # button for upper case characters button .c1 -side left -fill both -expand true pack .b1 -text "exit" \ -font "-family arial -weight bold -size $font_size" \ -background #ff0000 -command { exit } # pack the buttons pack .b0 -text "B4" \ -font "-family arial -weight bold -size $font_size" \ -background #8080e0 -command { P_process_button "button button .b0 -side top pack .c0.b1 -text "B3" \ -font "-family arial -weight bold -size $font_size" \ -background #8080e0 -command { P_process_button "button button .b0 -text "B0" \ -font "-family arial -weight bold -size $font_size" \ -background #8080e0 -command { P_process_button "button button .tcl #----------------------------------------------------------# button command processor proc P_process_button { button_cmd_string } { puts $button_cmd_string return } # set the font size (pts) set font_size 24 # frames for columns frame .c1.c1.b0 -side top pack .b0 -text "B2" \ -font "-family arial -weight bold -size $font_size" \ -background #8080e0 -command { P_process_button "button button .c0 frame .c2.c2 -side left -fill both -expand true Page 32 .March 31.c2.c1.b1 -text "B1" \ -font "-family arial -weight bold -size $font_size" \ -background #8080e0 -command { P_process_button "button button .c1.1 button 0001 0002 0003 0004 0005 0006 0007 0008 0009 0010 0011 0012 0013 0014 0015 0016 0017 0018 0019 0020 0021 0022 0023 0024 0025 0026 0027 0028 0029 0030 0031 0032 0033 0034 0035 0036 0037 0038 0039 0040 0041 0042 0043 0044 0045 0046 0047 0048 0049 0050 #!/usr/bin/wish #----------------------------------------------------------# example: ex_button.b1 -side top pack . 2002 Introduction to Tcl/Tk 14.c0 -side left -fill both -expand true pack .

2 label 0001 0002 0003 0004 0005 0006 0007 0008 0009 0010 0011 0012 0013 0014 0015 0016 0017 0018 0019 0020 0021 0022 0023 0024 0025 0026 0027 0028 0029 0030 0031 0032 0033 0034 0035 0036 0037 0038 0039 0040 0041 0042 0043 0044 0045 0046 0047 #!/usr/bin/wish #----------------------------------------------------------# example: ex_label.l0 -side top -fill both \ -expand true -padx $xpadding -pady $ypadding pack .c0.c0.c0.l0 configure -text $current_string -width $display_width return } # display adjustments tk scaling 1 set font_size 24 set display_width 10 set xpadding 10 set ypadding 10 # setup the current label string set current_string "OFF" # frame for column 0 frame .b0 -side top -fill both pack .l0 -text $current_string \ -font "-family arial -weight bold -size $font_size" \ -width $display_width # pack the label.March 31.c0 Page 33 .tcl #----------------------------------------------------------proc P_process_button { } { global current_string global display_width if { [string compare $current_string "OFF"] == 0 } { set current_string "ON" } else { set current_string "OFF" } .b0 -text "toggle" \ -font "-family arial -weight bold -size $font_size" \ -background #808080 -command P_process_button # label widget label . 2002 Introduction to Tcl/Tk 14. and column pack .c0. button.c0 # button button .c0.

tcl #----------------------------------------------------------proc P_contact_entry { } { frame .March 31.exit_button -text "exit" \ -command { exit } pack pack pack pack pack pack pack pack pack .email_label -side top -fill x -expand true .last_name_label -text "last name" entry .contact_frame.3 entry 0001 0002 0003 0004 0005 0006 0007 0008 0009 0010 0011 0012 0013 0014 0015 0016 0017 0018 0019 0020 0021 0022 0023 0024 0025 0026 0027 0028 0029 0030 0031 0032 0033 0034 0035 0036 0037 0038 0039 0040 0041 0042 0043 0044 0045 0046 #!/usr/bin/wish #----------------------------------------------------------# example: ex_entry.save_button .contact_frame.contact_frame. 2002 Introduction to Tcl/Tk 14.save_button -text "save" \ -command { P_save_contact $last_name $phone $email } button .phone_entry -side top -fill x -expand true .phone_entry -textvariable phone -width 20 label .contact_frame.last_name_entry -side top -fill x -expand true .email_entry -side top -fill x -expand true .exit_button .contact_frame. } P_contact_entry Page 34 .contact_frame.phone_label -side top -fill x -expand true .contact_frame -borderwidth 2 -relief raised label .contact_frame.last_name_entry -textvariable last_name -width 40 label .email_label -text "email" entry .contact_frame.phone_label -text "phone" entry .contact_frame.contact_frame.email_entry -textvariable email -width 40 button .contact_frame -fill both -expand true return } proc P_save_contact { last_name phone email } { puts "<contact>" puts " <last_name>$last_name</last_name>" puts " <phone>$phone</phone>" puts " <email>$email</email>" puts "</contact>" return.last_name_label -side top -fill x -expand true .contact_frame.contact_frame.contact_frame.contact_frame.contact_frame.contact_frame.

txtwin -width 80 -height 20 -bg grey \ -yscrollcommand ". 2002 Introduction to Tcl/Tk 14. "Text Widget Example" # text widget with y scroll bar text .4 text 0001 0002 0003 0004 0005 0006 0007 0008 0009 0010 0011 0012 0013 0014 0015 0016 0017 0018 0019 #!/usr/bin/wish #----------------------------------------------------------# example: ex_text.txtwin -side left -fill y # pack the scrollbar pack .yscroll -side right -fill y Page 35 .yscroll set" # scrollbar widget scrollbar .March 31.yscroll -command ".tcl #----------------------------------------------------------# title on main window wm title .txtwin yview" # pack the text window pack .

msg.txtwin yview" pack .msg.msg -side top -fill both -expand true return } set editor "gvim" P_menu Page 36 .msg.menupull add command \ -label "Exit" -command { exit } text .file.5 menu 0001 0002 0003 0004 0005 0006 0007 0008 0009 0010 0011 0012 0013 0014 0015 0016 0017 0018 0019 0020 0021 0022 0023 0024 0025 0026 0027 0028 0029 0030 0031 0032 0033 0034 0035 0036 #!/usr/bin/wish #----------------------------------------------------------# example: ex_menu.file.March 31.file -text "file" -menu .menupull menu .txtwin -side left -expand true -fill both pack .msg.yscroll set" # scrollbar widget scrollbar .msg.file -side left pack .mbar -side top -fill x pack .mbar.yscroll -side left -fill y pack .mbar.file.menupull .txtwin -width 80 -height 20 -bg grey \ -yscrollcommand ".tcl #----------------------------------------------------------proc P_menu { } { global editor frame .mbar.file.msg.mbar. 2002 Introduction to Tcl/Tk 14.mbar.mbar -borderwidth 2 -relief raised frame .yscroll -command ".menupull add command \ -label "Edit" -command { exec $editor } .msg -borderwidth 2 -relief raised menubutton .mbar.

c -width 400 -height 100 \ -scrollregion {0 0 800 400}] pack .y) $y } proc CanvasDrag { x y can } { global canvas # Map from view coordinates to canvas coordinates set x [$can canvasx $x] set y [$can canvasy $y] Page 37 .6 canvas 0001 0002 0003 0004 0005 0006 0007 0008 0009 0010 0011 0012 0013 0014 0015 0016 0017 0018 0019 0020 0021 0022 0023 0024 0025 0026 0027 0028 0029 0030 0031 0032 0033 0034 0035 0036 0037 0038 0039 0040 0041 0042 0043 0044 0045 0046 0047 0048 0049 0050 0051 0052 #!/usr/bin/wish #----------------------------------------------------------# example: ex_canvas.canvas } proc CanvasHello {} { set can [Scrolled_Canvas . World!" -tag movable # Bind actions to objects with the movable tag $can bind movable <Button-1> {CanvasMark %x %y %W} $can bind movable <B1-Motion> {CanvasDrag %x %y %W} } proc CanvasMark { x y can } { global canvas # Map from view coordinates to canvas coordinates set x [$can canvasx $x] set y [$can canvasy $y] # Remember the object and its location set canvas($can.yscroll set] \ -highlightthickness 0 \ -borderwidth 0} $args scrollbar $c.obj) [$can find closest $x $y] set canvas($can.canvas \ -xscrollcommand [list $c.yscroll -orient vertical \ -command [list $c.canvas yview] grid $c.yscroll -sticky news grid $c. 3rd Edition # written by Brent Welsh #----------------------------------------------------------proc Scrolled_Canvas { c args } { frame $c eval {canvas $c.canvas $c.tcl # this example was combined from examples 34-1 and 34-2 # Practical Programming in Tcl and Tk. 2002 Introduction to Tcl/Tk 14.x) $x set canvas($can.c -fill both -expand true # Create a text object on the canvas $can create text 50 50 -text "Hello.xscroll -sticky ew grid rowconfigure $c 0 -weight 1 grid columnconfigure $c 0 -weight 1 return $c.canvas xview] scrollbar $c.March 31.xscroll -orient horizontal \ -command [list $c.xscroll set] \ -yscrollcommand [list $c.

x) $x set canvas($can.y) $y } CanvasHello pack .c -fill both -expand true Introduction to Tcl/Tk Page 38 .$canvas($can. 2002 0053 0054 0055 0056 0057 0058 0059 0060 0061 0062 # Move the current object set dx [expr $x .y)] $can move $canvas($can.$canvas($can.March 31.obj) $dx $dy set canvas($can.x)] set dy [expr $y .

NJ. The History of Tcl. Academic Press.lang. Dr. Brent B. 2000 [2] Nelson.activestate. http://tcl. ISBN 0-12-261205-1.com/ [11] ActiveState Tcl. John K...net/ Page 39 .tcl [8] Tcl Consortium. ISBN 013461674X. Prentice Hall.html [7] USENET. Practical Programming in Tcl and Tk. Third Edition. Tcl and the Tk Toolkit. Clif.tclforeda. Dr. 1999 [4] Young. Prentice Hall. The Visual Tcl Handbook.com/ [10] ActiveState. David H. ISBN 0-13-022028-0. John K. http://www. 0-201-63337-X. Tcl/Tk Programmers Reference.tclconsortium.org/resources/ [9] Scriptics.. Upper Saddle River.. Tcl/Tk for Real Programmers. 2600 Tenth Street.scriptics. 1996 [5] Ousterhout. http://tcl. http://www. CA. 1994 [6] Ousterhout. Berkeley. comp. http://www. 2002 Introduction to Tcl/Tk References [1] Welch.activestate.March 31. Addison-Wesley Publishing. http://www. 94710. Osborne McGraw-Hill. ISBN 0-07-212004-5. Christopher.activestate.com/advocacy/tclHistory. 2000 [3] Flynt.com/ [12] Tcl for EDA.