NEW TITLE RELEASE ANNOUNCEMENT
See the latest about a temporary release delay on new titles. Learn more.
The Tcl scripting language and the Tk toolkit - a programming environment for creating graphical user interfaces under X Windows - together represent one of the most exciting innovations in X Window System programming. Because Tcl and Tk are so easy to learn, extremely powerful, and contain so many sophisticated features, they have dramatically reduced development time for thousands of X programmers.
Written by the creator of Tcl and Tk, this book is the single authoritative resource for anyone who wants to work with this extraordinary environment. The book offers an introduction and overview of Tcl and Tk and then presents detailed instructions for script writing in Tcl and working with the Tk toolkit.
You will discover how Tk's windowing shell, wish, enables you to develop window-based applications with amazingly few lines of code. You will also find information on Tk's novel and powerful facility for linking applications. Many other features are also described, such as Tk's hypertext and hypergraphics widgets and Tcl's facilities for procedures, list management, and subprocess execution.
For interested readers, the book also describes the C interfaces for Tcl and Tk, showing how to extend their built-in features by writing new C commands.
Upon reading this book, you will learn how to produce far more powerful X Windows System applications in a fraction of the time that used to be required.
"The main guide to Tcl is Tcl and the Tk Toolkit by John Ousterhout (Reading, MA: Addison-Wesley, 1994), the creator of Tcl."
- Unix Review
"The definitive source of information on the system is John Ousterhout's book, Tcl and the Tk Toolkit, published by Addison-Wesley."
- Linux Journal
"Overall, Ousterhout has provided an excellent overview (Tcl and the Tk Toolkit)of a very useful piece of software. If you're thinking of building or customizing a graphical user interface, you won't find many guides better than this."
- IEEE Computer
"This is an extremely well-written book, containing many figures, tables, examples, and scripts to illustrate the Tcl and Tk concepts. His presentation technique and expertise result in a superb text. I enjoyed Tcl and the Tk Toolkit and recommend it highly to anyone with any shell writing experience. Everyone who uses the X Window System will find this book helpful."
- Sys Admin
Tk 4.0 Overview and Porting Guide (a PostScript file of additional material not included in the printed book)
Organization of the Book.
Hello World with Tk.
Variables and Substitutions.
On the Tcl Language.
Additional Features of Tcl and Tk.
Extensions and Applications.
I. THE TCL LANGUAGE.3. Tcl Language Syntax.
Scripts, Commands, and Words
Evaluating a Command.
Quoting with Double Quotes.
Quoting With Braces.
Normal and Exceptional Returns.
More on Substitutions.4. Variables.
Simple Variables and the Set Command.
Removing Variables: Unset.
The Incr and Append Commands.
Preview of Other Variable Facilities.5. Expressions.
Operators and Precedence.
Types and Conversions.
Basic List Structure and the Lindex Command.
Creating Lists: Concat, List, and Llength.
Modifying Lists: Linsert, Lreplace, Lrange, and Lappend.
Searching Lists: Lsearch.
Sorting Lists: Lsort.
Converting Between Strings and Lists: Split and Join.
Lists and Commands.7. Control Flow.
The If Command.
Looping Commands: While, For, and Foreach.
Loop Control: Break and Continue.
The Switch Command.
The Eval Command.
Executing From Files: Source.8. Procedures.
Procedure Basics: Proc and Return.
Local and Global Variables.
Defaults and Variable Numbers of Arguments.
Call By Reference: Upvar.
Creating New Control Structures: Uplevel.9. String Manipulation.
Character Set Issues.
Glob-Style Pattern Matching.
Pattern Matching with Regular Expressions.
Using Regular Expressions for Substitutions.
Generating Strings with Format.
Parsing Strings With Scan.
Extracting Characters: String Index and String Range.
Searching and Comparison.
Length, Case Conversion, and Trimming.10. Accessing Files.
Basic File I/O.
Random Access to Files.
The Current Working Directory.
Manipulating File Names: Glob and File.
File Information Commands.
Errors in System Calls.11. Processes.
Invoking Subprocesses with Exec.
I/O To and From a Command Pipeline.
Terminating the Tcl Process with Exit.12. Errors and Exceptions.
What Happens after an Error?
Generating Errors from Tcl Scripts.
Trapping Errors with Catch.
Exceptions in General.13. Managing Tcl Internals.
Querying the Elements of an Array.
The Info Command.
Timing Command Execution.
Tracing Operations on Variables.
Renaming and Deleting Commands.
The History List.
Reexecuting Commands from the History List.
Shortcuts Implemented by Unknown.
Current Event Number: History Nextid.
II. WRITING SCRIPTS FOR TK.15. An Introduction to Tk.
A Brief Introduction to X.
Applications, Top-Level Widgets, and Screens.
Scripts and Events.
Creating and Destroying Widgets.
Commands for Interconnection.16. A Tour of the Tk Widgets.
Buttons, Checkbuttons, and Radiobuttons.
Menus and Menubuttons.
Other Common Options.17. Geometry Managers: the Packer.
An Overview of Geometry Management.
The Pack Command and -Side Options.
Other Options to the Pack Command.
Other Geometry Managers in Tk.18. Bindings.
An Overview of the Bind Command.
Sequences of Events.
Substitutions in Scripts.
When are Events Processed?
Background Errors: Tkerror.
Other Uses of Bindings.19. Canvas and Text Widgets.
Canvas Basics: Items and Types.
Manipulating Items with Identifiers and Tags.
Other Canvas Features.
Text Indices and Marks.
Text Tags.20. The Selection.
Selections, Retrievals, and Targets.
Locating and Clearing the Selection.
Supplying the Selection with Tcl Scripts.21. The Input Focus.
Focus Model: Explicit vs. Implicit.
Setting The Input Focus.
Clearing The Focus.
The Default Focus.
Shortcuts.22. Window Managers.
Window Manager Protocols.
Special Handling: Transients, Groups, and Override-Redirect.
A Warning about Window Managers.23. The Send Command.
Security Issues.24. Modal Interactions.
Keyboard Handling During Grabs.
Waiting: The Tkwait Command.25. More on Configuration Options.
The Option Database.
Option Database Entries.
The RESOURCE_MANAGER Property and .Xdefaults File.
Priorities in the Option Database.
The Option Command.
The Configure Widget Command.26. Odds and Ends.
The Update Command.
Information about Widgets.
Raise and Lower.
The Tk Command: Color Models.
Variables Managed by Tk.27. Examples.
A Procedure that Generates Dialog Boxes.
A Remote-Control Application.
III. WRITING TCL APPLICATIONS IN C.28. Philosophy.
C vs. Tcl: Primitives.
Commands: Action-Oriented vs. Object-Oriented.
Representing Information.29. Interpreters and Script Evaluation.
A Simple Tcl Application.
Other Evaluation Procedures.
Deleting Interpreters.30. Creating New Tcl Commands.
The Result Protocol.
Procedures for Managing the Result.
Clientdata and Deletion Callbacks.
How Tcl Procedures Work.31. Tcl_AppInit and Packages.
Defining Packages.32. Parsing.
Numbers and Booleans.
Manipulating Lists.33. Exceptions.
Augmenting the Stack Trace in errorInfo.
Setting errorCode.34. Accessing Tcl Variables.
Setting Variable Values.
Linking Tcl and C Variables.
Setting and Unsetting Variable Traces.
Querying Trace Information.35. Hash Tables.
Keys and Values.
Creating and Deleting Hash Tables.
Finding Existing Entries.
Statistics.36. String Utilities.
String Matching.37. POSIX Utilities.
IV. TK'S C INTERFACES.38. Introduction.
What's in a Widget?
The Relationship Between Tk and Xlib.
Square: An Example Widget.
Design for Reusability.39. Creating Windows.
Windows and Tk_Windows.
Setting a Window's Class.
Basic Operations on Tk_Windows.
Class Command Procedures.
Delayed Window Creation.40. Configuring Widgets.
Changing Window Attributes.
The Square Configure Procedure.
The Square Widget Command Procedure.41. Events.
Generic Event Handlers.
Invoking the Event Dispatcher.42. Displaying Widgets.
Double-Buffering with Pixmaps.
Drawing Procedures.43. Destroying Widgets.
Delayed Cleanup.44. Managing the Selection.
Claiming the Selection.
Retrieving the Selection.45. Geometry Management.
Requesting a Size for a Widget.
Retrieving Geometry Information.
Mapping and Setting Geometry.
Writing Geometry Managers.Appendix A. Installing Tcl and Tk.
The Master Directory.
Retrieving Distributions with FTP.
Retrieving Distributions with Electronic Mail.
Compiling and Installing the Distributions.
Comp.lang.tcl newsgroup.Index. 020163337XT04062001
Tcl was born of frustration. In the early 1980s my students and I developed a number of interactive tools at the University of California at Berkeley, mostly for integrated circuit design, and we found ourselves spending a lot of time building bad command languages. Each tool needed to have a command language of some sort, but our main interest was in the tool rather than its command language. We spent as little time as possible on the command language and always ended up with a language that was weak and quirky. Furthermore, the command language for one tool was never quite right for the next tool, so we ended up building a new bad command language for each tool. This became increasingly frustrating.
In the fall of 1987 it occurred to me that the solution was to build a reusable command language. If a general-purpose scripting language could be built as a C library package, then perhaps it could be reused for many different purposes in many different applications. Of course, the language would need to be extensible so that each application could add its own specific features to the core provided by the library. In the spring of 1988 I decided to implement such a language, and the result was Tcl.
Tk was also born of frustration. The basic idea for Tk arose in response to Apple's announcement of HyperCard in the fall of 1987. HyperCard generated tremendous excitement because of the power of the system and the way in which it allowed many different interactive elements to be scripted and work together. However, I was discouraged. The HyperCard system had obviously taken a large development effort, and it seemed unlikely to me that a small group such as a university research project could ever mount such a massive effort. This suggested that we would not be able to participate in the development of new forms of interactive software in the future.
I concluded that the only hope for us was a component approach. Rather than building a new application as a self-contained monolith with hundreds of thousands of lines of code, we needed to find a way to divide applications into many smaller reusable components. Ideally each component would be small enough to be implemented by a small group, and interesting applications could be created by assembling components. In this environment it should be possible to create an exciting new application by developing one new component and then combining it with existing components.
The component-based approach requires a powerful and flexible "glue"for assembling the components, and it occurred to me that perhaps a shared scripting language could provide that glue. Out of this thinking grew Tk, an X11 toolkit based on Tcl. Tk allows components to be either individual user-interface controls or entire applications; in either case components can be developed independently and Tcl can be used to assemble the components and communicate between them.
I started writing Tcl and Tk as a hobby in my spare time. As other people began to use the systems I found myself spending more and more time on them, to the point where today they occupy almost all of my waking hours and many of my sleeping ones.
Tcl and Tk have succeeded beyond my wildest dreams. The Tcl/Tk developer community now numbers in the tens of thousands and there are thousands of Tcl applications in existence or under development. The application areas for Tcl and Tk cover virtually the entire spectrum of graphical and engineering applications, including computer-aided design, software development, testing, instrument control, scientific visualization, and multimedia. Tcl is used by itself in many applications, and Tcl and Tk are used together in many others. Tcl and Tk are being used by hundreds of companies, large and small, as well as universities and research laboratories.
One benefit that came as a surprise to me is that it is possible to create interesting graphical user interfaces (GUIs) entirely as Tcl scripts. I had always assumed that every Tcl application would contain some new C code that implements new Tcl commands, plus some Tcl scripts that combine the new commands with the built-in facilities provided by Tcl. However, once a simple Tcl/Tk application called wish became available, many people began creating user interfaces by writing Tcl scripts for it, without writing any C code at all! It turned out that the Tcl and Tk commands provide a high-level interface to GUI programming that hides many of the details faced by a C programmer. As a result, it is much easier to learn how to use wish than a C-based toolkit, and user interfaces can be written with much less code. Most Tcl/Tk users never write any C code at all and most of the Tcl/Tk applications consist solely of Tcl scripts.
This book is intended as an introduction to Tcl and Tk for programmers who plan to write or modify Tcl/Tk applications. I assume that readers have programmed in C and have at least passing familiarity with a shell such as sh or csh or ksh. I also assume that readers have used the X Window System and are familiar with basic ideas such as using the mouse, resizing windows, etc. No prior experience with Tcl or Tk is needed in order to read this book, and you need not have written X applications using other toolkits such as Motif.
The book is organized so that you can learn Tcl without learning Tk if you wish. Also, the discussion of how to write Tcl scripts is separate from the discussion of how to use the C library interfaces provided by Tcl and Tk. The first two parts of the book describe Tcl and Tk at the level of writing scripts, and the last two parts describe the C interfaces for Tcl and Tk; if you are like the majority of Tcl/Tk users who only write scripts, you can stop after reading the first two parts.
In spite of my best efforts, I'm sure that there are errors in this edition of the book. I'm interested in hearing about any problems that you encounter, whether they are typos, formatting errors, sections or ideas that are hard to understand, or bugs in the examples. I'll attempt to correct the problems in future printings of the book. The best way to report problems is with electronic mail sent to firstname.lastname@example.org.
Many people have helped in the creation of this book. First and foremost I would like to thank Brian Kernighan, who reviewed several drafts of the manuscript with almost terrifying thoroughness and uncovered numerous problems both large and small. I am also grateful for the detailed comments provided by the other Addison-Wesley technical reviewers: Richard Blevins, Gerard Holzmann, Curt Horkey, Ron Hutchins, Stephen Johnson, Oliver Jones, David Korn, Bill Leggett, Don Libes, Kent Margraf, Stuart McRobert, David Richardson, Alexei Rodrigues, Gerald Rosenberg, John Slater, and Win Treese. Thanks also to Bob Sproull, who read the next-to-last draft from cover to cover and provided countless bug fixes and suggestions.
I made early drafts of the manuscript available to the Tcl/Tk community via the Internet and received countless comments and suggestions from all over the world in return. I'm afraid that I didn't keep careful enough records to acknowledge all the people who contributed in this way, but the list of contributors includes at least the following people: Marvin Aguero, Miriam Amos Nihart, Jim Anderson, Frederik Anheuser, Jeff Blaine, John Boller, David Boyce, Terry Brannon, Richard Campbell, J. Cazander, Wen Chen, Richard Cheung, Peter Chubb, De Clarke, Peter Collinson, Peter Costantinidis, Alistair Crooks, Peter Davies, Tal Dayan, Akim Demaille, Mark Diekhans, Matthew Dillon, Tuan Doan, Tony Duarte, Paul DuBois, Anton Eliens, Marc R. Ewing, Luis Fernandes, Martin Forssen, Ben Fried, Matteo Frigo, Andrej Gabara, Steve Gaede, Sanjay Ghemawat, Bob Gibson, Michael Halle, Jun Hamano, Stephen Hansen, Brian Harrison, Marti Hearst, Fergus Henderson, Kevin Hendrix, David Herron, Patrick Hertel, Carsten Heyl, Leszek Holenderski, Jamie Honan, Rob W.W. Hooft, Nick Hounsome, Christopher Hylands, Jonathan Jowett, Poul-Henning Kamp, Karen L. Karavanic, Sunil Khatri, Vivek Khera, Jon Knight, Roger Knopf, Ramkumar Krishnan, Dave Kristol, Peter LaBelle, Tor-Erik Larsen, Tom Legrady, Will E. Leland, Kim Lester, Joshua Levy, Don Libes, Oscar Linares, David C.P. Linden, Toumas J. Lukka, Steve Lord, Steve Lumetta, Earlin Lutz, David J. Mackenzie, B.G. Mahesh, John Maline, Graham Mark, Stuart McRobert, George Moon, Michael Morris, Russell Nelson, Dale K. Newby, Richard Newton, Peter Nguyen, David Nichols, Marty Olevitch, Rita Ousterhout, John Pierce, Stephen Pietrowicz, Anna Pluzhnikov, Nico Poppelier, M.V.S. Ramanath, Cary D. Renzema, Mark Roseman, Samir Tiongson Saxena, Jay Schmidgall, Dan M. Serachitopol, Hume Smith, Frank Stajano, Larry Streepy, John E. Stump, Michael Sullivan, Holger Teutsch, Bennett E. Todd, Glenn Trewitt, D.A. Vaughan-Pope, Richard Vieregge, Larry W. Virden, David Waitzman, Matt Wartell, Glenn Waters, Wally Wedel, Juergen Weigert, Mark Weiser, Brent Welch, Alex Woo, Su-Lin Wu, Kawata Yasuro, Chut Ngeow Yee, Richard Yen, Stephen Ching-SingYen, and Mike Young.
Many many people have made significant contributions to the development of Tcl and Tk. Without all of their efforts there would have been nothing of interest to write about in this book. Although I cannot hope to acknowledge all the people who helped to make Tcl and Tk what they are today, I would like to thank the following people specially: Don Libes, for writing the first widely used Tcl application; Mark Diekhans and Karl Lehenbauer, for TclX; Alastair Fyfe, for supporting the early development of Tcl; Mary Ann May-Pumphrey, for developing the original Tcl test suite; George Howlett, Michael McLennan, and Sani Nassif, for the BLT extensions; Kevin Kenny, for showing that Tcl can be used to communicate with almost any imaginable program; Joel Bartlett, for many challenging conversations and for inspiring Tk's canvas widget with his ezd program; Larry Rowe, for developing Tcl-DP and for providing general advice and support; Sven Delmas, for developing the XF application builder based on Tk; and Andrew Payne, for the widget tour and for meritorious Tcl evangelism.
Several companies have provided financial support for the development of Tcl and Tk, including Digital Equipment Corporation, Hewlett-Packard Corporation, Sun Microsystems, and Computerized Processes Unlimited. I am particularly grateful to Digital's Western Research Laboratory and its director, Richard Swan, for providing me with a one-day-per-week hideaway where I could go to gather my thoughts and work on Tcl and Tk.
Terry Lessard-Smith and Bob Miller have provided fabulous administrative support for this and all my other projects. I don't know how I would get anything done without them.
Finally, I owe a special debt to my colleague and friend Dave Patterson, whose humor and sage advice have inspired and shaped much of my professional career, and to my wife Rita and daughters Kay and Amy, who have tolerated my workaholic tendencies with more cheer and affection than I deserve.