The Tcl/Tk best-seller, now completely updated for Tcl 8.2 and the Tcl Web Server!
Tcl/Tk 8.2 is the first scripting language that can handle enterprise-wide integration tasks that encompass Windows, Solaris, Macintosh, and other key platforms. Now, in this fully updated Third Edition, Tcl/Tk development team member and best-selling author Brent Welch presents all you need to know to achieve powerful results with Tcl/Tk 8.2 and the new Tcl Web Server.
You'll find extensive coverage of user interface development, as well as application integration techniques that leverage Tcl/Tk's powerful cross-platform scripting capabilities. Welch covers Tcl's extensive network support, as well as Safe Tcl, C programming with the Tk toolkit, the Tcl compiler, and Tcl/Tk plug-ins for Netscape and Internet Explorer. Whether you're a current Tcl/Tk programmer, or a developer searching for a convenient, powerful multiplatform scripting language, Practical Programming in Tcl and Tk, Third Edition delivers exactly what you're looking for.
"This is an excellent book, loaded with useful examples. Newcomers to Tk will find the widget descriptions particularly helpful." --John Ousterhout CEO and founder of Scriptics Corporation and the creator of Tcl/Tk
"Brent Welch fills an important need for an introduction to Tcl/Tk with an applied focus and with coverage of many of the useful extensions available . . . I recommend this book to my new students . . . and I keep a copy handy for my own use." --Joseph A. Konstan, Professor of Computer Science University of Minnesota
ABOUT THE CD-ROM
The accompanying CD-ROM includes the Tcl Web Server; Tcl/Tk distributions for Windows 9x/NT, Solaris, and Macintosh; plus an extensive collection of free Tcl/Tk software-including all the code from the book.
Art: Include the same boxed quotes that appeared on the 2e back cover.
Click here for a sample chapter for this book: 0130220280.pdf
I. TCL BASICS.1. Tcl Fundamentals.
Tcl Commands. Hello, World! Variables. Command Substitution. Math Expressions. Backslash Substitution. Grouping with Braces and Double Quotes. Square Brackets Do Not Group. Grouping before Substitution. Grouping Math Expressions with Braces. More Substitution Examples. Procedures. A Factorial Example. More about Variables. Funny Variable Names. The unset Command. Using info to Find Out about Variables. More about Math Expressions. Comments. Substitution and Grouping Summary. Fine Points. Reference. Backslash Sequences. Arithmetic Operators. Built-in Math Functions. Core Tcl Commands.2. Getting Started.
The source Command. UNIX Tcl Scripts. Windows 95 Start Menu. The Macintosh and ResEdit. The console Command. Command-Line Arguments. Command-Line Options to Wish. Predefined Variables.3. The Guestbook CGI Application.
A Quick Introduction to HTML. CGI for Dynamic Pages. The guestbook.cgi Script. Using a Script Library File. Beginning the HTML Page. Simple Tags and Hypertext Links. Using a Tcl Array for the Database. Sample Output. Defining Forms and Processing Form Data. The newguest.html Form. The newguest.cgi Script. The cgi.tcl Package. Next Steps.4. String Processing in Tcl.
The string Command. String Indices. Strings and Expressions. String Matching. Character Classes. Mapping Strings. The append Command. The format Command. The scan Command. The binary Command. Format Templates. Examples. Binary Data and File I/O. Related Chapters.5. Tcl Lists.
Tcl Lists. Constructing Lists. The list command. The lappend Command. The concat Command. Getting List Elements: llength, lindex, and lrange. Modifying Lists: linsert and lreplace. Searching Lists: lsearch. Sorting Lists: lsort. The split Command. The join Command. Related Chapters.6. Control Structure Commands.
If Then Else. Switch. Comments in switch Commands. While. Foreach. Multiple Loop Variables. Multiple Value Lists. For. Break and Continue. Catch. Catching More Than Errors. Error. Return.7. Procedures and Scope.
The proc Command. Changing Command Names with rename. Scope. The global Command. Call by Name Using upvar. Variable Aliases with upvar. Associating State with Data. Namespaces and upvar. Commands That Take Variable Names.8. Tcl Arrays.
Array Syntax. Complex Indices. Array Variables. The array Command. Converting Between Arrays and Lists. Passing Arrays by Name. Building Data Structures with Arrays. Simple Records. A Stack. A List of Arrays. A Simple In-Memory Database.9. Working with Files and Programs.
Running Programs with exec. The auto_noexec Variable. Limitations of exec on Windows. AppleScript on Macintosh. The file Command. Cross-Platform File Naming. Building up Pathnames: file join. Chopping Pathnames: split, dirname, tail. Manipulating Files and Directories. Copying Files. Creating Directories. Deleting Files. Renaming Files and Directories. File Attributes. Input/Output Command Summary. Opening Files for I/O. Opening a Process Pipeline. Expect. Reading and Writing. The puts and gets Commands. The read Command. Platform-Specific End of Line Characters. Random Access I/O. Closing I/O Channels. The Current Directory ÷ cd and pwd. Matching File Names with glob. Expanding Tilde in File Names. The exit and pid Commands. Environment Variables. The registry Command.
II. ADVANCED TCL.10. Quoting Issues and Eval.
Constructing Code with the list Command. The eval Command. Commands That Concatenate Their Arguments. Commands That Use Callbacks. Command Prefix Callbacks. Constructing Procedures Dynamically. Exploiting the concat inside eval. Using eval in a Wrapper Procedure. Correct Quoting with eval. The uplevel Command. The subst Command. String Processing with subst.11. Regular Expressions.
When to Use Regular Expressions. Avoiding a Common Problem. Regular Expression Syntax. Matching Characters. Character Sets. Quantifiers. Alternation. Anchoring a Match. Backslash Quoting. Matching Precedence. Capturing Subpatterns. Advanced Regular Expressions. Compatibility with Patterns in Tcl 8.0. Backslash Escape Sequences. Character Classes. Nongreedy Quantifiers. Bound Quantifiers. Back References. Look-ahead. Character Codes. Collating Elements. Equivalence Classes. Newline Sensitive Matching. Embedded Options. Expanded Syntax. Syntax Summary. The regexp Command. A Pattern to Match URLs. Sample Regular Expressions. The regsub Command. Transforming Data to Program with regsub. URL Decoding. CGI Argument Parsing. Decoding HTML Entities. A Simple HTML Parser. Stripping HTML Comments. Other Commands That Use Regular Expressions.12. Script Libraries and Packages.
Locating Packages: The auto_path Variable. Using Packages. Loading Packages Automatically. Packages Implemented in C Code. Summary of Package Loading. The package Command. Libraries Based on the tclIndex File. The unknown Command. How Auto Loading Works. Disabling the Library Facility: auto_noload. Interactive Conveniences. Auto Execute. History. Abbreviations. Tcl Shell Library Environment. Locating the Tcl Script Library. tcl_findLibrary. Coding Style. A Module Prefix for Procedure Names. A Global Array for State Variables. The Official Tcl Style Guide.13. Reflection and Debugging.
The clock Command. The info Command. Variables. Procedures. The Call Stack. Command Evaluation. Scripts and the Library. Version Numbers. Execution Environment. Cross-Platform Support. Tracing Variable Values. Read-Only Variables. Creating an Array with Traces. Interactive Command History. History Syntax. A Comparison to C Shell History Syntax. Debugging. Scripticsâ TclPro. TclPro Debugger. TclPro Checker. TclPro Compiler. TclPro Wrapper. Other Tools. The tkinspect Program. The Tuba Debugger. The bgerror Command. The tkerror Command. Performance Tuning. Time stamps in a Log. The Tcl Compiler.14. Namespaces.
Using Namespaces. Namespace Variables. Qualified Names. Command Lookup. Nested Namespaces. Importing and Exporting Procedures. Callbacks and Namespaces. Introspection. The namespace Command. Converting Existing Packages to use Namespaces. [incr Tcl] Object System. Notes. Names for Widgets, Images, and Interpreters. The variable command at the global scope. Auto Loading and auto_import. Namespaces and uplevel. Naming Quirks. Miscellaneous.15. Internationalization.
Character Sets and Encodings. The System Encoding. File Encodings and fconfigure. Scripts in Different Encodings. Unicode and UTF-8. The Binary Encoding. Conversions Between Encodings. The encoding Command. Message Catalogs. Specifying a Locale. Managing Message Catalog Files. Message Catalogs and Namespaces. The msgcat package.16. Event-Driven Programming.
The Tcl Event Loop. The after Command. The fileevent Command. The vwait Command. The fconfigure Command. Nonblocking I/O. The fblocked Command. Buffering. End of Line Translations. End of File Character. Serial Devices. Character Set Encodings. Configuring Read-Write Channels.17. Socket Programming.
Client Sockets. Client Socket Options. Server Sockets. Server Socket Options. The Echo Service. Fetching a URL with HTTP. Proxy Servers. The HEAD Request. The GET and POST Requests. The fcopy Command. The http Package. http::config. http::geturl. http::formatQuery. http::reset. http::cleanup. Basic Authentication.18. TclHttpd Web Server.
Integrating TclHttpd with your Application. TclHttpd Architecture. Domain Handlers. Connection State and Query Data. Returning Results. Application Direct URLs. Using Query Data. Returning Other Content Types. Document Types. HTML + Tcl Templates. Where to put your Tcl Code. Templates for Site Structure. Form Handlers. Application Direct Handlers. Template Form Handlers. Self Posting Forms. The form package. Programming Reference. Standard Application-Direct URLs. Status. Debugging. Administration. Sending Email. The TclHttpd Distribution. Quick Start. Inside the Distribution. Server Configuration. Command Line Arguments. Server Name and Port. User and Group ID. Webmaster Email. Document Root. Other Document Settings. Document Templates. Log Files. CGI Directories.19. Multiple Interpreters and Safe-Tcl.
The interp Command. Creating Interpreters. The Interpreter Hierarchy. The Interpreter Name as a Command. Use list with interp eval. Safe Interpreters. Command Aliases. Alias Introspection. Hidden Commands. Substitutions. I/O from Safe Interpreters. The Safe Base. Security Policies. Limited Socket Access. Limited Temporary Files. Safe after Command.20. Safe-Tk and the Browser Plugin.
Tk in Child Interpreters. Embedding Tk Windows. Safe-Tk Restrictions. The Browser Plugin. The embed_args and plugin Variables. Example Plugins. Setting Up the plugin. Plugin Environment Variables. UNIX Configuration. Windows Configuration. Macintosh Configuration. Security Policies and Browser Plugin. The Browser Package. Configuring Security Policies. The config/plugin.cfg File. Policy Configuration Files. Security Policy Features. Creating New Security Policies.
III. TK BASICS.21. Tk Fundamentals.
Hello, World! in Tk. Naming Tk Widgets. Configuring Tk Widgets. Tk Widget Attributes and the Resource Database. The Tk Manual Pages. Summary of the Tk Commands.22. Tk by Example.
ExecLog. Window Title. A Frame for Buttons. Command Buttons. A Label and an Entry. Key Bindings and Focus. A Resizable Text and Scrollbar. The Run Procedure. The Log Procedure. The Stop Procedure. Cross-Platform Issues. The Example Browser. More about Resizing Windows. Managing Global State. Searching through Files. Cascaded Menus. A Read-Only Text Widget. A Tcl Shell. Text Marks, Tags, and Bindings. Multiple Interpreters. Native Look and Feel.23. The Pack Geometry Manager.
Packing toward a Side. Shrinking Frames and pack propagate. Horizontal and Vertical Stacking. The Cavity Model. Packing Space and Display Space. The -fill Option. Internal Padding with -ipadx and -ipady. External Padding with -padx and -pady. Resizing and -expand. Anchoring. Packing Order. Introspection. Pack the Scrollbar First. Choosing the Parent for Packing. Unpacking a Widget. Packer Summary. The pack Command. Window Stacking Order.24. The Grid Geometry Manager.
A Basic Grid. The -sticky Setting. External Padding with -padx and -pady. Internal Padding with -ipadx and -ipady. Multiple Widgets in a Cell. Spanning Rows and Columns. Row and Column Constraints. Row and Column Padding. Minimum Size. Managing Resize Behavior. The grid Command.25. The Place Geometry Manager.
place Basics. The Pane Manager. Parsing Arguments and Maintaining State. Sticky Geometry Settings. Event Bindings. Managing the Layout. The place Command.26. Binding Commands to Events.
The bind Command. The bindtags Command. Focus and Key Events. Using break and continue in Bindings. Defining New Binding Tags. Event Syntax. Keyboard Events. Mouse Events. Other Events. Bindings on Top-level Windows. Modifiers. Event Sequences. Virtual Events. Event Keywords.
IV. TK WIDGETS.27. Buttons and Menus.
Button Commands and Scope Issues. Buttons Associated with Tcl Variables. Button Attributes. Button Operations. Menus and Menubuttons. A Menu Bar. System Menus. Pop-Up Menus. Option Menus. Multicolumn Palette Menus. Keyboard Traversal. Manipulating Menus and Menu Entries. Menu Attributes. A Menu by Name Package. Menu Accelerators.28. The Resource Database.
An Introduction to Resources. Resource Patterns. Loading Option Database Files. Adding Individual Database Entries. Accessing the Database. User-Defined Buttons. User-Defined Menus. Application and User Resources. Expanding Variables.29. Simple Tk Widgets.
Frames and Toplevel Windows. Attributes for Frames and Toplevels. Embedding Other Applications. Toplevel Window Styles. The Label Widget. Label Width and Wrap Length. Label Attributes. The Message Widget. Message Attributes. Arranging Labels and Messages. The Scale Widget. Scale Bindings. Scale Attributes. Programming Scales. The bell Command.30. Scrollbars.
Using Scrollbars. The Scrollbar Protocol. The Scrollbar set Operation. The xview and yview Operations. The Tk 3.6 Protocol. The Scrollbar Widget. Scrollbar Bindings. Scrollbar Attributes. Programming Scrollbars.31. The Entry Widget.
Using Entry Widgets. Tips for Using Entry Widgets. The Entry Widget. Entry Attributes. Programming Entry Widgets.32. The Listbox Widget.
Using Listboxes. Programming Listboxes. Listbox Bindings. Browse Select Mode. Single Select Mode. Extended Select Mode. Multiple Select Mode. Scroll Bindings. Listbox Attributes. Geometry Gridding.33. The Text Widget.
Text Indices. Inserting and Deleting Text. Indexs Arithmetic. Comparing Indices. Text Marks. Mark Gravity. Text Tags. Tag Attributes. Mixing Attributes from Different Tags. Line Spacing and Justification. Tab Stops. The Selection. Tag Bindings. Searching Text. Embedded Widgets. Embedded Images. Looking inside the Text Widget. Looking at Tags. Looking at Marks. Dumping the Contents. Text Bindings. Text Operations. Text Attributes.34. The Canvas Widget.
Canvas Coordinates. Hello, World! Canvas Tags. The Min Max Scale Example. Canvas Objects. Arc Items. Bitmap Items. Image Items. Line Items. Oval Items. Polygon Items. Rectangle Items. Text Items. Window Items. Canvas Operations. Generating Postscript. Canvas Attributes. Hints. Screen Coordinates vs Canvas Coordinates. Large Coordinate Spaces. Scaling and Rotation. Resources. Objects with Many Points. Selecting Canvas Items.
V. TK DETAILS.35. Selections and the Clipboard.
The Selection Model. The selection Command. The clipboard Command. Selection Handlers. A Canvas Selection Handler.36. Focus, Grabs, and Dialogs.
Standard Dialogs. Message Box. File Dialogs. Color Dialog. Custom Dialogs. Input Focus. The focus Command. Keyboard Focus Traversal. Grabbing the Focus. The tkwait Command. Destroying Widgets. The focus, grab, tkwait sequence. Prompter Dialog. Keyboard Shortcuts and Focus. Animation with the update Command.37. Tk Widget Attributes.
Configuring Attributes. Size. Borders and Relief. The Focus Highlight. Padding and Anchors. Putting It All Together.38. Color, Images, and Cursors.
Colors. Color Palettes. Color Values. Colormaps and Visuals. Bitmaps and Images. The image Command. Bitmap Images. The bitmap Attribute. Photo Images. The Text Insert Cursor. The Mouse Cursor.39. Fonts and Text Attributes.
Naming a Font. Named Fonts. System Fonts. Unicode Fonts. X Font Names. Font Failures before Tk 8.0. Font Metrics. The font Command. Text Attributes. Layout. Selection Attributes. Gridding, Resizing, and Geometry. A Font Selection Application.40. Send.
The send Command. Send and X Authority. The Sender Script. Communicating Processes. Remote eval through Sockets.41. Window Managers and Window Information.
The wm Command. Size, Placement, and Decoration. Icons. Session State. Miscellaneous. The winfo Command. Sending Commands between Applications. Family Relationships. Size. Location. Virtual Root Window. Atoms and IDs. Colormaps and Visuals. The tk Command.42. Managing User Preferences.
App-Defaults Files. Defining Preferences. The Preferences User Interface. Managing the Preferences File. Tracing Changes to Preference Variables. Improving the Package.43. A User Interface to Bindings.
A Pair of Listboxes Working Together. The Editing Interface. Saving and Loading Bindings.
VI. C PROGRAMMING.44. C Programming and Tcl.
Basic Concepts. Getting Started. C Command Procedures and Data Objects. SWIG. Tcl Initialization. Calling Out to Tcl Scripts. Using the Tcl C Library. Creating a Loadable Package. The load Command. The Package Initialization Procedure. Using Tcl_PkgProvide. A C Command Procedure. The String Command Interface. Result Codes from Command Procedures. Managing the String Result. The Tcl_Obj Command Interface. Managing Tcl_Obj Reference Counts. Modifying Tcl_Obj Values. Pitfalls of Shared Tcl_Obj Values. The blob Command Example. Creating and Destroying Hash Tables. Tcl_Alloc and Tcl_Free. Parsing Arguments and Tcl_GetIndexFromObj. Creating and Removing Elements from a Hash Table. Building a List. Keeping References to Tcl_Obj Values. Using Tcl_Preserve and Tcl_Release to Guard Data. Strings and Internationalization. The DString Interface. Character Set Conversions. Tcl_Main and Tcl_AppInit. Tk_Main. The Event Loop. Invoking Scripts from C. Variations on Tcl_Eval. Bypassing Tcl_Eval.45. Compiling Tcl and Extensions.
Standard Directory Structure. The Source Distribution. The Installation Directory Structure. Building Tcl from Source. Configure and Autoconf. Standard Configure Flags. Installation. Using Stub Libraries. Using autoconf. The tcl.m4 File. Makefile Templates. The Sample Extension. configure.in. Makefile.in. Standard Header Files. Using the Sample Extension.46. Writing a Tk Widget in C.
Initializing the Extension. The Widget Data Structure. The Widget Class Command. The Widget Instance Command. Configuring and Reconfiguring Attributes. Specifying Widget Attributes. Displaying the Clock. The Window Event Procedure. Final Cleanup.47. C Library Overview.
An Overview of the Tcl C Library. Application Initialization. Creating and Deleting Interpreters. Creating and Deleting Commands. Dynamic Loading and Packages. Managing the Result String. Memory Allocation. Lists. Command Parsing. Command Pipelines. Tracing the Actions of the Tcl Interpreter. Evaluating Tcl Commands. Reporting Script Errors. Manipulating Tcl Variables. Evaluating Expressions. Converting Numbers. Tcl Objects. Primitive Object Types. String Object Types. ByteArrays for Binary Data. Dynamic Strings. Character Set Encodings. AssocData for per Interpreter Data Structures. Hash Tables. Option Processing. Regular Expressions and String Matching. Event Loop Implementation. File Handlers. Timer Events. Idle Callbacks. Input/Output. I/O Channel Drivers. Manipulating File Names. Examining the File System. Thread Support. Working with Signals. Exit Handlers. An Overview of the Tk C Library. Main Programs and Command-Line Arguments. Creating Windows. Application Name for Send. Configuring Windows. Window Coordinates. Window Stacking Order. Window Information. Configuring Widget Attributes. The Selection and Clipboard. Event Loop Interface. Handling Window Events. Event Bindings. Handling Graphic Protocol Errors. Using the Resource Database. Managing Bitmaps. Creating New Image Types. Using an Image in a Widget. Photo Image Types. Canvas Object Support. Geometry Management. String Identifiers (UIDS). Colors, Colormaps, and Visuals. 3D Borders. Mouse Cursors. Fonts and Text Display. Graphics Contexts. Allocate a Pixmap. Screen Measurements. Relief Style. Text Anchor Positions. Line Cap Styles. Line Join Styles. Text Justification Styles. Atoms. X Resource ID Management.
VII. CHANGES.48. Tcl 7.4/Tk 4.0.
wish. Obsolete Features. The cget Operation. Input Focus Highlight. Bindings. Scrollbar Interface. pack info. Focus. The send Command. Internal Button Padding. Radiobutton Value. Entry Widget. Menus. Listboxes. No geometry Attribute. Text Widget. Color Attributes. Color Allocation and tk colormodel. Canvas scrollincrement. The Selection. The bell Command.49. Tcl 7.5/Tk 4.1.
Cross-Platform Scripts. File Name Manipulation. Newline Translations. The tcl_platform Variable. The console Command. The clock Command. The load Command. The package Command. Multiple foreach loop variables. Event Loop Moves from Tk to Tcl. Network Sockets. info hostname. The fconfigure Command. Multiple Interpreters and Safe-Tcl. The grid Geometry Manager. The Text Widget. The Entry Widget.50. Tcl 7.6/Tk 4.2.
More file Operations. Virtual Events. Standard Dialogs. New grid Geometry Manager. Macintosh unsupported1 Command.51 Tcl/Tk 8.0.
The Tcl Compiler. Compile-Time Errors. Binary String Support. Namespaces. Safe-Tcl. New lsort. tcl_precision Variable. Year 2000 Convention. Http Package. Serial Line I/O. Platform-Independent Fonts. The tk scaling Command. Application Embedding. Native Menus and Menubars. CDE Border Width. Native Buttons and Scrollbars. Images in Text Widgets. No Errors from destroy. grid rowconfigure. The Patch Releases. fconfigure -error. tcl_platform(debug). tcl_findLibrary. auto_mkindex_old. Windows Keysyms for Start and Menu Keys. The MouseWheel Event. Transparent Fill on Canvas Text. safe::loadTk.52 Tcl/Tk 8.1.
Unicode and Internationalization. fconfigure -encoding. The encoding Command. The msgcat Package. UTF-8 and Unicode C API. Thread Safety. The testthread Command. Advanced Regular Expressions. New String Commands. The DDE Extension. Miscellaneous. Serial Line I/O. tcl_platform(user).53 Tcl/Tk 8.2.
The Trf Patch. Faster String Operations. Empty Array Names. Browser Plugin Compatibility.54 Tcl/Tk 8.3.
Proposed Tcl Changes. Octal Numbers. file channels. Changing File Modify Times. regsub -subst or -command. New glob options. Internationalization. Proposed Tk Changes. The Img Patch. Canvas Improvements. Pointer Warping. Hidden Text. Entry Widget Validation.55 About The CD-ROM.
Tcl stands for Tool Command Language Tcl is really two things: a scripting language, and an interpreter for that language that is designed to be easy to embed into your application. Tcl and its associated graphical user-interface toolkit, Tk, were designed and crafted by Professor John Ousterhout of the University of California, Berkeley. You can find these packages on the Internet (as explained on page lii) and use them freely in your application, even if it is commercial. The Tcl interpreter has been ported from UNIX to DOS, Windows, OS/2, NT, and Macintosh environments. The Tk toolkit has been ported from the X window system to Windows and Macintosh.
I first heard about Tcl in 1988 while I was Ousterhout's Ph.D. student at Berkeley. We were designing a network operating system, Sprite. While the students hacked on a new kernel, John wrote a new editor and terminal emulator. He used Tcl as the command language for both tools so that users could define menus and otherwise customize those programs. This was in the days of X10, and he had plans for an X toolkit based on Tcl that would help programs cooperate with each other by communicating with Tcl commands. To me, this cooperation among tools was the essence of Tcl.
This early vision imagined that applications would be large bodies of compiled code and a small amount of Tcl used for configuration and high-level commands. John's editor, mx, and the terminal emulator, tx, followed this model. While this model remains valid, it has also turned out to be possible to write entire applications in Tcl. This is because the Tcl/Tk shell, wish, provides access to other programs, the file system, network sockets, plus the ability to create a graphical user interface. For better or worse, it is now common to find applications that contain thousands of lines of Tcl script.
This book was written because, while I found it enjoyable and productive to use Tcl and Tk, there were times when I was frustrated. In addition, working at Xerox PARC, with many experts in languages and systems, I was compelled to understand both the strengths and weaknesses of Tcl and Tk. Although many of my colleagues adopted Tcl and Tk for their projects, they were also just as quick to point out its flaws. In response, I have built up a set of programming techniques that exploit the power of Tcl and Tk while avoiding troublesome areas. This book is meant as a practical guide to help you get the most out of Tcl and Tk and avoid some of the frustrations I experienced.
It has been about 10 years since I was introduced to Tcl, and about five years since the first edition of this book. During the last several years I have been working under John Ousterhout, first at Sun Microsystems and now at Scriptics Corporation. I have managed to remain mostly a Tcl programmer while others in our group have delved into the C implementation of Tcl itself. I've been building applications like HTML editors, e-mail user interfaces, Web servers, and the customer database we run our business on. This experience is reflected in this book. The bulk of the book is about Tcl scripting, and the aspects of C programming to create Tcl extensions is given a lighter treatment. I have been lucky to remain involved in the core Tcl development, and I hope I can pass along the insights I have gained by working with Tcl.
As a scripting language, Tcl is similar to other UNIX shell languages such as the Bourne Shell (sh), the C Shell (csh), the Korn Shell (ksh), and Perl. Shell programs let you execute other programs. They provide enough programmability (variables, control flow, and procedures) to let you build complex scripts that assemble existing programs into a new tool tailored for your needs. Shells are wonderful for automating routine chores.
It is the ability to easily add a Tcl interpreter to your application that sets it apart from other shells. Tcl fills the role of an extension language that is used to configure and customize applications. There is no need to invent a command language for your new application, or struggle to provide some sort of user-programmability for your tool. Instead, by adding a Tcl interpreter, you structure your application as a set of primitive operations that can be composed by a script to best suit the needs of your users. It also allows other programs to have programmatic control over your application, leading to suites of applications that work well together.
The Tcl C library has clean interfaces and is simple to use. The library implements the basic interpreter and a set of core scripting commands that implement variables, flow control, and procedures (see page 22). There is also a set of commands that access operating system services to run other programs, access the file system, and use network sockets. Tk adds commands to create graphical user interfaces. Tcl and Tk provide a "virtual machine" that is portable across UNIX, Windows, and Macintosh environments.
The Tcl virtual machine is extensible because your application can define new Tcl commands. These commands are associated with a C or C++ procedure that your application provides. The result is applications that are split into a set of primitives written in a compiled language and exported as Tcl commands. A Tcl script is used to compose the primitives into the overall application. The script layer has access to shell-like capability to run other programs, has access to the file system, and can call directly into the compiled part of the application through the Tcl commands you define. In addition, from the C programming level, you can call Tcl scripts, set and query Tcl variables, and even trace the execution of the Tcl interpreter.
There are many Tcl extensions freely available on the Internet. Most extensions include a C library that provides some new functionality, and a Tcl interface to the library. Examples include database access, telephone control, MIDI controller access, and expect, which adds Tcl commands to control interactive programs.
The most notable extension is Tk, a toolkit for graphical user interfaces. Tk defines Tcl commands that let you create and manipulate user interface widgets. The script-based approach to user interface programming has three benefits:
Java has exploded onto the computer scene since this book was first published. Java is a great systems programming language that in the long run could displace C and C++. This is fine for Tcl, which is designed to glue together building blocks written in any system programming language. Tcl was designed to work with C, but has been adapted to work with the Java Virtual Machine. Where I say "C or C++", you can now say "C, C++, or Java," but the details are a bit different with Java. This book does not describe the Tcl/Java interface, but you can find TclBlend on the CD-ROM. TclBlend loads the Java Virtual Machine into your Tcl application and lets you invoke Java methods. It also lets you implement Tcl commands in Java instead of C or C++.
Tcl and Tk Versions
Tcl and Tk continue to evolve. See
http://www.beedub.com/book/ for updates and news about the latest Tcl releases. Tcl and Tk have had separate version numbers for historical reasons, but they are released in pairs that work together. The original edition of this book was based on Tcl 7.4 and Tk 4.0, and there were a few references to features in Tk 3.6. This third edition has been updated to reflect new features added through Tcl/Tk 8.2:
gridgeometry manager introduced in Tk 4.1. Cross-platform support includes virtual events (e.g.,
<<Copy>>as opposed to
<Control-c>),standard dialogs, and more file manipulation commands.
Who Should Read This Book
This book is meant to be useful to the beginner in Tcl as well as the expert. For the beginner and expert alike, I recommend careful study of Chapter 1, Tcl Fundamentals. The programming model of Tcl is designed to be simple, but it is different from many programming languages. The model is based on string substitutions, and it is important that you understand it properly to avoid trouble in complex cases. The remainder of the book consists of examples that demonstrate how to use Tcl and Tk productively. For your reference, each chapter has tables that summarize the Tcl commands and Tk widgets they describe.
This book assumes that you have some programming experience, although you should be able to get by even if you are a complete novice. Knowledge of UNIX shell programming will help, but it is not required. Where aspects of window systems are relevant, I provide some background information. Chapter 2 describes the details of using Tcl and Tk on UNIX, Windows, and Macintosh.
How to Read This Book
This book is best used in a hands-on manner, trying the examples at the computer. The book tries to fill the gap between the terse Tcl and Tk manual pages, which are complete but lack context and examples, and existing Tcl programs that may or may not be documented or well written.
I recommend the on-line manual pages for the Tcl and Tk commands. They provide a detailed reference guide to each command. This book summarizes much of the information from the manual pages, but it does not provide the complete details, which can vary from release to release. HTML versions of the on-line manual pages can be found on the CD-ROM that comes with this book.
Other Tcl Books
This book was the second Tcl book after the original book by John Ousterhout, the creator of Tcl. Since then, the number of Tcl books has increased remarkably. The following are just some of the books currently available.
Tcl and the Tk Toolkit (Addison-Wesley, 1994) by John Ousterhout provides a broad overview of all aspects of Tcl and Tk, even though it covers only Tcl 7.3 and Tk 3.6. The book provides a more detailed treatment of C programming for Tcl extensions.
Exploring Expect (O'Reilly & Associates, Inc., 1995) by Don Libes is a great book about an extremely useful Tcl extension. Expect lets you automate the use of interactive programs like ftp and telnet that expect to interact with a user. By combining expect and Tk, you can create graphical user interfaces for old applications that you cannot modify directly.
Graphical Applications with Tcl & Tk (M&T Press, 1996) by Eric Johnson is oriented toward Windows users. The second edition is up-to-date with Tcl/Tk 8.0.
Tcl/Tk Tools (O'Reilly & Associates, Inc., 1997) by Mark Harrison describes many useful Tcl extensions. These include Oracle and Sybase interfaces, object-oriented language enhancements, additional Tk widgets, and much more. The chapters were contributed by the authors of the extensions, so they provide authoritative information on some excellent additions to the Tcl toolbox.
CGI Developers Resource, Web Programming with Tcl and Perl (Prentice Hall, 1997) by John Ivler presents Tcl-based solutions to programming Web sites.
Effective Tcl/Tk Programming (Addison Wesley, 1997) by Michael McLennan and Mark Harrison illustrate Tcl and Tk with examples and application design guidelines.
Interactive Web Applications with Tcl/Tk (AP Professional, 1998) by Michael Doyle and Hattie Schroeder describes Tcl programming in the context of the Web browser plugin.
Tcl/Tk for Programmers (IEEE Computer Society, 1998) by Adrian Zimmer describes Unix and Windows programming with Tcl/Tk. This book also includes solved exercises at the end of each chapter.
Tcl/Tk for Real Programmers (Academic Press, 1999) by Clif Flynt is another example-oriented book.
Tcl/Tk in a Nutshell (O'Reilly, 1999) by Paul Raines and Jeff Tranter is a handy reference guide. It covers several popular extensions including Expect, incr Tcl, Tix, TclX, BLT, SybTcl, OraTcl, and TclODBC. There is a tiny pocket-reference guide for Tcl/Tk that may eliminate the need to thumb through my large book to find the syntax of a particular Tcl or Tk command.
Web Tcl Complete (McGraw Hill, 1999) by Steve Ball describes programming with the Tcl Web Server. It also covers Tcl/Java integration using TclBlend. incr Tcl From The Ground Up (Osborn-McGraw Hill, 1999) by Chad Smith describes the incr Tcl object-oriented extension to Tcl.
The book comes with a CD-ROM that has source code for all of the examples, plus a selection of Tcl freeware found on the Internet. The CD-ROM is created with the Linux mkhybrid program, so it is readable on UNIX, Windows, and Macintosh. There, you will find the versions of Tcl and Tk that were available as the book went to press. You can also retrieve the sources shown in the book from my personal Web site:
The primary site for the Tcl and Tk distributions is given below as a Universal Resource Location (URL):
You can use FTP and log in to the host (e.g.,
ftp.scriptics.com) under the
anonymous user name. Give your e-mail address as the password. The directory is in the URL after the host name (e.g.,
/pub/tcl). There are many sites that mirror this distribution. The mirror sites provide an archive site for contributed Tcl commands, Tk widgets, and applications. There is also a set of Frequently Asked Questions files. These are some of the sites that maintain Tcl archives:
ftp://ftp.neosoft.com/pub/tcl ftp://ftp.syd.dit.csiro.au/pub/tk ftp://ftp.ibp.fr/pub/tcl ftp://src.doc.ic.ac.uk/packages/tcl/ ftp://ftp.luth.se/pub/unix/tcl/ ftp://sunsite.cnlab-switch.ch/mirror/tcl ftp://ftp.sterling.com/programming/languages/tcl ftp://ftp.sunet.se/pub/lang/tcl ftp://ftp.cs.columbia.edu/archives/tcl ftp://ftp.uni-paderborn.de/pub/unix/tcl ftp://sunsite.unc.edu/pub/languages/tcl ftp://ftp.funet.fi/pub/languages/tcl
You can use a World Wide Web browser like Mosaic, Netscape, Internet Explorer, or Lynx to access these sites. Enter the URL as specified above, and you are presented with a directory listing of that location. From there you can change directories and fetch files.
If you do not have direct FTP access, you can use an e-mail server for FTP. Send e-mail to
firstname.lastname@example.org with the message
Help to get directions. If you are on BITNET, send e-mail to
You can search for FTP sites that have Tcl by using the Archie service that indexes the contents of anonymous FTP servers. Information about using Archie can be obtained by sending mail to
email@example.com that contains the message
World Wide Web
Start with these World Wide Web pages about Tcl:
http://www.scriptics.com/ http://www.sco.com/Technology/tcl/Tcl.html http://www.purl.org/NET/Tcl-FAQ/
The home page for this book contains errata for all editions. This is the only URL I control personally, and I plan to keep it up-to-date indefinitely:
The Prentice Hall Web site has information about the book, but you must use its search facility to find the exact location. Start at:
comp.lang.tcl newsgroup is very active. It provides a forum for questions and answers about Tcl. Announcements about Tcl extensions and applications are posted to the
The chapters of the book are divided into seven parts. The first part describes basic Tcl features. The first chapter describes the fundamental mechanisms that characterize the Tcl language. This is an important chapter that provides the basic grounding you will need to use Tcl effectively. Even if you have programmed in Tcl already, you should review Chapter 1. Chapter 2 goes over the details of using Tcl and Tk on UNIX, Windows, and Macintosh. Chapter 3 presents a sample application, a CGI script, that illustrates typical Tcl programming. The rest of Part I covers the basic Tcl commands in more detail, including string handling, data types, control flow, procedures, and scoping issues. Part I finishes with a description of the facilities for file I/O and running other programs.
Part II describes advanced Tcl programming. It starts with
eval, which lets you generate Tcl programs on the fly. Regular expressions provide powerful string processing. If your data-processing application runs slowly, you can probably boost its performance significantly with the regular expression facilities. Namespaces partition the global scope of procedures and variables. Unicode and message catalogs support internationalized applications. Libraries and packages provide a way to organize your code for sharing among projects. The introspection facilities of Tcl tell you about the internal state of Tcl. Event driven I/O helps server applications manage several clients simultaneously. Network sockets are used to implement the HTTP protocol used to fetch pages on the World Wide Web. Safe-Tcl is used to provide a secure environment to execute applets downloaded over the network. TclHttpd is an extensible web server built in Tcl. You can build applications on top of this server, or embed it into your existing applications to give them a web interface.
Part III introduces Tk. It gives an overview of the toolkit facilities. A few complete examples are examined in detail to illustrate the features of Tk. Event bindings associate Tcl commands with events like keystrokes and button clicks. Part III ends with three chapters on the Tk geometry managers that provide powerful facilities for organizing your user interface.
Part IV describes the Tk widgets. These include buttons, menus, scrollbars, labels, text entries, multiline and multifont text areas, drawing canvases, list-boxes, and scales. The Tk widgets are highly configurable and very programmable, but their default behaviors make them easy to use as well. The resource database that can configure widgets provides an easy way to control the overall look of your application.
Part V describes the rest of the Tk facilities. These include selections, keyboard focus, and standard dialogs. Fonts, colors, images, and other attributes that are common to the Tk widgets are described in detail. This part ends with a few larger Tk examples.
Part VI is an introduction to C programming and Tcl. The goal of this part is to get you started in the right direction when you need to extend Tcl with new commands written in C or integrate Tcl into custom applications.
Part VII provides a chapter for each of the Tcl/Tk releases covered by the book. These chapters provide details about what features were changed and added. They also provide a quick reference if you need to update a program or start to use a new version.
What's New in the Third Edition
The third edition is up-to-date with Tcl/Tk 8.2. The main new Tcl/Tk features are Internationalization, which is covered in Chapter 15, a new regular expression engine, which is described in Chapter 11, and thread-safety. There is a new chapter about compiling C extensions, and there is a more complete C extension example. The chapters on Eval and the Web browser plugin received a thorough update. I made a light sweep through the remainder of the book correcting errors and improving examples. Perhaps the best addition for the reader is an all-new index.
My favorite addition to the book is Chapter 18 that describes TclHttpd, a Web server built in Tcl. TclHttpd provides a number of nice ways to integrate a Web server with a Tcl application, replacing the standard CGI interface with something that is much more flexible and efficient. I have been using this server for the last year to build
www.scriptics.com. This freely available server has been used to build several other products, plus it provides an easy way for you to bring up your own Web server.
Contact the Author
I am always open to comments about this book. My e-mail address is
firstname.lastname@example.org. It helps me sort through my mail if you put the word "book" or the title of the book into the e-mail subject line. Visit my Web site at:
for current news about the book and my other interests.