Chapter 1. Introducing Tcl and Tk

This is the one chapter in every book about programming languages that readers usually skip. It consists of a short history of Tcl and Tk, a section highlighting their salient features, and a recitation of their distinguishing characteristics (which bears a disturbing resemblance to marketing). While I hope you read, or at least skim, the entire chapter, if your computer doesn’t already have Tcl and Tk installed, then don’t skip “Getting Tcl and Tk,” or you won’t be able to work through the example programs, which would certainly defeat the purpose of buying this book.

What Is Tcl?

Tcl, pronounced like “tickle,” stands for tool command language. As the odd name suggests, Tcl was designed to be a glue language enabling users to control other programs and utilities. Tcl, and its graphical complement, Tk (discussed in the next section), were created by Dr. John Ousterhout at the University of California-Berkeley in the 1980s. As originally conceived, Dr. Ousterhout intended Tcl to be used both as a scripting language, allowing programs to communicate with each other by invoking Tcl commands, and as an embeddable interpreter in those programs, allowing users to configure and customize the programs using the Tcl scripting language they already knew. In this way, Tcl is roughly analogous to Visual Basic for Applications (VBA) from Microsoft. Just as you can use VBA to pull functionality from Microsoft Word, Excel, and PowerPoint into a single application, you can use Tcl (and Tk) to pull functionality from a variety of programs together into a single application.

Like any successful programming language or application, though, Tcl long ago met and exceeded its creator’s original intent. Originally built as a high-level tool to allow other programs to interact with each other, it is now much more common to encounter complete Tcl/Tk applications that consist of hundreds or thousands of lines of code. The capabilities of Tcl’s core language have grown as well so that Tcl programmers can create fully network-aware and -capable applications, interact with databases, browse the Web or serve Web pages, and control MIDI devices. Indeed, there are enough extensions to the language, written in Tcl itself or using its extensions API (application programming interface), that what you can do with Tcl is truly limited only by your imagination and your facility with the language.

Cross-platform. Did I mention that Tcl is cross-platform? Cross-platform means that the Tcl code you write on, for example, Linux should execute unmodified on any system to which the Tcl interpreter has been ported. Which is to say that Java is not the first language to claim: “Write once, run anywhere.” Tcl’s cross-platform capabilities free developers from having to learn the specifics of, say, interacting with the Linux file system or the Windows TCP/IP stack. Instead, the Tcl interpreter handles the low level, platform-specific details of writing to files or opening network sockets, freeing you to focus on your application, such as what you are going to write to a file or what you are going to do with the data you just read from that socket. It is certainly true that you need to have some platform-specific knowledge, such as the difference between how filenames are constructed on Windows and UNIX systems, but the point is that Tcl shields you from these low-level details.

What Is Tk?

At the simplest level, Tk (pronounced “tee kay”) is an extension to Tcl (strictly speaking, a library) that provides a toolkit for creating and using graphical user interfaces. Tk includes commands for creating buttons, text boxes, and other user interface widgets. You can also control the colors of Tk applications and the fonts that they use. Tk provides an interface to the graphical windowing system of the host operating system on which it is being executed. As a Tcl extension, Tk gives you access to all of Tcl’s core commands and other extensions.

Tk does for creating graphical applications what Tcl does for creating nongraphical applications. Usually, when you create a graphical application, you have to spend as much time developing the buttons, text boxes, and scroll bars and wiring them into your application as you do developing the application itself, that is, the logic and functionality for which the graphical components are merely an interface. Tk handles the difficulty and tedium of creating the graphical components, freeing your time and effort for the application itself.

Tk has a reputation for looking old and resulting in an awkward user interface. To some degree, this is deserved; Tk’s development lagged behind other toolkits. However, things have begun to change. A popular extension, Tile, is available that gives most Tk widgets the look and feel of their native operating system’s applications. Work is underway to integrate the Tile extension into the Tk core. In addition to providing a native look and feel to Tk applications, Tile supports the most recent trend in GUI customization, which are themes (also known as skins). So, while Tk might have been slow in the past to adapt to changes in windowing toolkits, it is quickly closing the gap.

What Makes Tcl and Tk Different?

What makes Tcl and Tk different from other programming languages and graphical toolkits? Tcl compares favorably to scripting languages like Perl, Python, and Ruby and shells such as Bourne, Korn, and Bash because it has the same features and capabilities, albeit with a different syntax and language structure. What distinguishes Tcl from other scripting languages is its ability to be embedded into other applications. It is relatively straightforward to add a Tcl interpreter to your existing application and so provide a full-featured configuration and macro language.

Tk, likewise, gives you access to the same basic user interface widgets as most other graphical toolkits. However, once you are familiar with Tk, you can write graphical applications faster with it than you can with other toolkits. Not many scripting languages offer graphical functionality as an integral part of the language. As a result, you can often, even routinely, develop an application in weeks using Tk, something that would have taken months with another language and graphical framework.

Finally, a graphical application developed with Tk can be remarkably short. The following three-line Tcl script displays a clock whose display updates every second:

proc every {ms body} {eval $body; after $ms [info level 0]}
pack [label .clock -textvar time]
every 1000 {set ::time [clock format [clock sec] -format %H:%M:%S]}

Don’t worry about the syntax and commands in this program, just appreciate the brevity of the code. You’ll understand what these commands do soon enough. Figures 1.1, 1.2, and 1.3 show what this clock looks like on Linux, Windows, and OS X, respectively.

A three-line Tk clock program running on Linux.

Figure 1.1. A three-line Tk clock program running on Linux.

A three-line Tk clock program running on Windows XP.

Figure 1.2. A three-line Tk clock program running on Windows XP.

A three-line Tk clock program running on OS X.

Figure 1.3. A three-line Tk clock program running on OS X.

Why Use Tcl and Tk?

I use Tcl and Tk for a number of reasons. First, it is fast, easy to use, and capable. Although Tcl will never win a foot race with a compiled language like C if you need to do heavy number crunching or 3D animation, for the majority of your needs, Tcl will be fast enough. It is also easy to use because the language itself consists of relatively few commands and a very small number of syntax rules. Tcl is also capable because a good deal of functionality is built into the core command set or is available as extensions. If you can’t find what you want, though, you can create a new command that does do what you want.

Tcl has remained true to its roots as a glue language, a way to glue external programs and utilities together into a single, coherent application. For example, one friend of mine used Tcl and a smidgen of Tk to create a spam tagging and reporting application. He wrote just enough Tcl and Tk code to provide a user interface that he can use to tag a message as spam and track the spam back to its source, using network monitoring and diagnostic utilities (ping and whois) and some DNS lookup tools.

You can work fast with Tcl and Tk. Tk-based development is much faster than traditional library- or framework-based development because Tk handles the mechanics of creating and manipulating graphical widgets. Moreover, as an interpreted language, Tcl spares you long compile times. Granted, the programs you will write and use in this book will be short, but as your own programs grow in length and complexity, you will appreciate being able to take the compile step out of the usual edit-compile-debug development process.

One of the most compelling reasons I can think of for using Tcl and Tk is that they are easy to learn and yet amply powerful. As I remarked earlier, Tcl has relatively few commands and an extremely simple syntax, so with a reasonable amount of practice, you will be able to write small but useful (and, in the case of this book, fun and entertaining) applications. At the same time, Tcl has all the elements you would expect in a programming language, such as variables, procedures, loops, conditionals, data structures, and interfaces to operating system services such as file I/O (input/output), process control, threads, and network sockets.

Finally, Tcl and Tk are satisfying and rewarding to use. If you are reading this book, you are probably already interested in programming and have experienced the sense of accomplishment that comes from writing a program that automates a tedious task or simplifies a complicated one. Tcl and Tk can satisfy that part of you that likes to build things. In my opinion, once you become proficient, Tcl and Tk shorten the time it takes you to get your reward: a completed program.

Getting Tcl and Tk

Obviously, in order to take advantage of Tcls and Tk’s benefits, you need to get them. Fortunately, this is not difficult. Tcl and Tk are freely available for a variety of operating systems. In most cases, you can get ready-to-run binaries. In other cases, you might have to download the source code and build it yourself. The instructions in this section describe how to obtain and install Tcl and Tk for the three most popular operating systems available: Linux, OS X, and Windows. I’ll also explain how to install Tcl and Tk from source, if binaries for your system are not available.

Installing Tcl and Tk on Linux

If you are running a Linux system, chances are better than average that you already have Tcl and Tk installed. Chances are better still that if you do not have it installed, it is readily available for installation from your vendor’s package repository or CD-ROM. For example, if you are using Fedora or Fedora Core, the following command should install the latest versions of Tcl and Tk:

# yum install tcl tk

On Debian-based systems, such as Debian itself or Ubuntu and its derivatives, the following command should suffice:

# sudo apt-get install tcl tk

I can’t provide instructions for every Linux distribution out there, but you get the idea. If a binary version of Tcl and Tk isn’t available for your favorite flavor of Linux, skip ahead to the section titled “Installing Tcl and Tk from Source.”

If you want to ensure that everything is working properly after the installation is complete, start the Tcl interpreter, tclsh, by typing tclsh at a command prompt and typing the following Tcl command at the % prompt:

% puts "Hello, Tcl/Tk World!"
Hello, Tcl/Tk World!
%

Installing Tcl and Tk on Windows

Installing Tcl and Tk on a Windows system is easy. First, point your Web browser at the ActiveState Web site (www.activestate.com), click Downloads, and click the ActiveTcl link under Language Downloads on the right-hand side of the page (see Figure 1.4).

Downloading ActiveTcl on Windows.

Figure 1.4. Downloading ActiveTcl on Windows.

You can either drop $40 to get a DVD shipped to you or click the Download link to start the download process. If you want to get promotional information from ActiveState, fill out the form. Otherwise, just click the Continue button. For Windows, you want the “AS Windows” package. “AS” stands for “ActiveState,” and the AS Windows package includes the Tcl download and ActiveState’s installer. The download weighs in at slightly less than 22MB (see Figure 1.5).

Select the ActiveTcl package for Windows.

Figure 1.5. Select the ActiveTcl package for Windows.

While the download proceeds, read the next paragraph to find out a little bit more about ActiveState and ActiveTcl.

ActiveState provides high quality software development products, such as Tcl, JavaScript, Perl, PHP, Python, and Ruby, and complementary tools such as integrated development environments and debuggers. In addition, ActiveState provides services for developers and for companies using ActiveState products. In most cases, their core products, like ActiveTcl, are free and licensed by their creators in such a way that the core languages, like Tcl and Tk, must be made available by companies like ActiveState for free. ActiveTcl is ActiveState’s binary distribution of Tcl, Tk, and a number of the most popular Tcl extensions. All of the extensions are tested, integrated, and ready to use. ActiveTcl closely tracks Tcl’s development, so it is as current and close to mainline Tcl as possible.

After you download the ActiveTcl installer, installation is quick and uncomplicated.

  1. Double-click the installer icon, which looks like a feather (a feather for tickling, get it?), as shown in Figure 1.6.

    ActiveState’s ActiveTcl installer icon.

    Figure 1.6. ActiveState’s ActiveTcl installer icon.

  2. After reviewing all the packages and extensions that will be installed, click Next (see Figure 1.7).

    ActiveTcl includes a rich set of extensions.

    Figure 1.7. ActiveTcl includes a rich set of extensions.

  3. Read the license (or not) and click Next to continue the installation (see Figure 1.8).

    Tedious and obligatory legalese.

    Figure 1.8. Tedious and obligatory legalese.

  4. If you have administrator rights on your Windows system, you can choose whether all users can use ActiveTcl or just the current user. Similarly, you can choose which file associations to allow the installer to make and modify the installation directory, which defaults to C:/Tcl, as shown in Figure 1.9. Make your selections and then click Next to proceed.

    Configure the Tcl installation.

    Figure 1.9. Configure the Tcl installation.

    No, the “/” is not a typo, and you don’t need glasses. Unlike Windows, UNIX and UNIX-like systems use “/” to separate directory names, not “”. Although "C:/Tcl" looks a bit odd, you’re just seeing an artifact of Tcl’s UNIX heritage peeking through. Not to worry, though, the installer does the right thing under the covers.

  5. On the next screen, you can choose where to install the demonstration applications. I recommend keeping it simple and accepting the default directory, C:/Tcl/demos (shown in Figure 1.10). Click Next to continue the installation.

    Decide where to install the demos.

    Figure 1.10. Decide where to install the demos.

  6. Confirm your selections on the Summary screen, illustrated in Figure 1.11, and then click Next to start (finally!) the installation.

    Ready to start the installation.

    Figure 1.11. Ready to start the installation.

    Again, the mixture of “/” and “” in directory names is unfortunate, but the installer really does work properly.

  7. The installation finishes quickly, and you’re left with the dialog box shown in Figure 1.12, which shows you some settings and a short ActiveState marketing blurb. Click the Finish button to close the installer.

    Success!

    Figure 1.12. Success!

If you want to ensure that everything is working properly after the installation is complete, start the Tcl interpreter, tclsh, by selecting Start → All Programs → ActiveState ActiveTcl 8.4.14.0 → Tclsh84 and typing the following Tcl commands at the % prompt:

% puts "Hello, Tcl/Tk World!"

If everything has gone as planned, the resulting output should look like Figure 1.13.

Verify that Tcl is properly installed.

Figure 1.13. Verify that Tcl is properly installed.

At this point, you’re ready to start learning Tcl.

Installing Tcl and Tk on OS X

Installing Tcl and Tk on an OS X system is as simple and uncomplicated as installing it on Windows. Browse to the ActiveState Web site (www.activestate.com), click Downloads, and then click the ActiveTcl link under Language Downloads on the right-hand side of the page (see Figure 1.14).

Finding the ActiveTcl package for OS X.

Figure 1.14. Finding the ActiveTcl package for OS X.

You can either drop $40 to get a DVD shipped to you or click the Download link to start the download process. If you want to get promotional information from ActiveState, fill out the resulting form. Otherwise, just click the Continue button. For OS X, you want the Mac OS X (Universal) package, which is an ActiveTcl package for both PPC and x86 versions of OS X. The download checks in at just less than 21MB (see Figure 1.15). After the download completes, use the following procedure to install ActiveTcl.

Downloading the ActiveTcl package for OS X.

Figure 1.15. Downloading the ActiveTcl package for OS X.

Double-click the package icon on the desktop (see Figure 1.16) to extract the archive.

Unpack the archive.

Figure 1.16. Unpack the archive.

Double-click the package icon, shown in Figure 1.17, to start the installation.

Start the installer.

Figure 1.17. Start the installer.

Figure 1.18 shows the items that the installer will install on your system. Click the Continue button to proceed.

View the components you are about to install.

Figure 1.18. View the components you are about to install.

You must agree to the ActiveState license if you are going to proceed with the installation (see Figure 1.19).

Accept the license to proceed.

Figure 1.19. Accept the license to proceed.

Select the destination into which to install the ActiveTcl package, as Figure 1.20 shows.

Choose the installation volume.

Figure 1.20. Choose the installation volume.

Figure 1.21 illustrates the installation progress bar. Watching the installation progress is about as exciting as watching paint dry.

Finally, the installation starts.

Figure 1.21. Finally, the installation starts.

At length, the installation completes successfully (see Figure 1.22).

A completed, successful installation.

Figure 1.22. A completed, successful installation.

If you want to ensure that everything is working properly after the installation is complete, start the Tcl interpreter, tclsh, by picking Applications → Utilities in Finder and double-clicking Wish 8.4 and typing the following Tcl command at the % prompt:

% puts "Hello, Tcl/Tk World!"

If everything has gone as planned, the resulting output should look like Figure 1.23.

Verify that Tcl is properly installed.

Figure 1.23. Verify that Tcl is properly installed.

At this point, you’re ready to start learning Tcl.

Installing Tcl and Tk from Source

Installing Tcl and Tk from source, as opposed to using a binary distribution, is the option of last resort. Not because it is difficult—it isn’t—and not because it is time consuming—it isn’t. Rather, it is a last resort simply because it’s a darned rare platform (that is, combination of operating system and CPU) for which stable releases of Tcl and Tk are unavailable in binary format. I’m showing you how to build your own Tcl and Tk binaries for two reasons. In the first place, telling you how to build them from source is simply a matter of completeness. Secondly, and this is the really important reason, if you want to play with the latest and greatest Tcl and Tk releases, you have to use the development versions (8.5.mumble as I write this sentence), which are rarely available in binary form.

Note: For Linux Users Only

Note: For Linux Users Only

The procedure I describe in this section is only for Linux users. OS X and Windows users should really use the binary distributions because building software on either of these platforms is complicated and usually requires expensive tools that you probably don’t have. Even for Linux users, you’ll need to have development packages installed, including g++ (the C++ compiler from the GNU project).

“Why would I want to use an unstable development version?” I’m glad you asked. You might want to play with its nifty new features. You might have encountered a bug in the stable release (yes, it’s true, there are bugs in the code, even after 20 years), the solution for which is available in a development release. You might want to see if programs that work flawlessly in Tcl and Tk 8.4 work just as flawlessly in Tcl and Tk 8.5. Or you might like living on the bleeding edge and using development code that could crash your system, eat your lunch, burn your coffee, stain your shirt, and steal your girlfriend. Whatever your reason for wanting to do so, this section shows you how to install Tck and Tk from source code.

Without going into the gory details, you can download source tarballs of Tcl and Tk from the Tcl/Tk Web site at www.tcl.tk/software/. For this example, I downloaded the source release of Tcl/Tk 8.5a5, a development version, which consisted of two compressed tar files, tcl8.5a5-src.tar.gz and tk8.5a5-src.tar.gz. You need to build Tcl first, because Tk depends on it, that is, Tk needs files provided by Tcl in order to build successfully and execute properly.

  1. Uncompress and extract the archive file:

    $ tar zxf tcl8.5a5-src.tar.gz
  2. cd into the tcl8.5a5 directory:

    $ cd tcl8.5a5
  3. cd into the unix directory:

    $ cd unix
  4. Configure the build system:

    $ ./configure –prefix=/opt –enable-gcc
    ...
    config.status: creating Makefile
    config.status: creating dltest/Makefile
    config.status: creating tclConfig.sh

    The argument—prefix=/opt tells the configure script where you want to install the compiled Tcl binaries. Traditionally, programs installed by system administrators which are not part of the system installation have usually been installed in /usr/local. On my system, I prefer to use the /opt filesystem. Wherever you install Tcl, I recommend installing it in a location that won’t be overwritten if/when you upgrade your system. The—enable-gcc argument tells the configure script to configure the build to use gcc, the GNU Compiler Collection, rather than another C compiler that might be installed on your system. In most cases, it isn’t necessary to use this argument, but it doesn’t hurt anything to do so.

  5. Build it:

    $ make
    ...
    gcc -pipe -O2    -Wl,—export-dynamic  tclAppInit.o -L/home/kurt/tclbook/tcl8.5a5/unix -
     ltcl8.5 -ldl   -lieee -lm 
                     -Wl,-rpath,/opt/lib -o tclsh

    While the build proceeds, get a cup of coffee.

  6. Run the test suite:

    $ make test
    ...
     3       unknownFailure
     521     win
     5       xdev

    While the test suite runs, get another cup of coffee. It isn’t uncommon to see tests skipped, so you can probably disregard messages about skipped tests. However, if you see more than a few failed tests, and you are motivated, you might consider reporting them to the Tcl developers using the Tcl bug tracker at sourceforge.net/tracker/?group_id=10894&atid=110894&func=add.

  7. Install the Tcl binaries and libraries. This step requires root access. On my system, I use sudo. Use the method that suits you for becoming root on your system:

    $ sudo make install
    ...
    Installing and cross-linking top-level (.1) docs
    Installing and cross-linking C API (.3) docs
    Installing and cross-linking command (.n) docs

After successfully installing Tcl, you build and install Tk much the same way:

  1. Uncompress and extract the Tk archive file:

    $ tar zxf tk8.5a5-src.tar.gz
  2. cd into the tk8.5a5 directory:

    $ cd tk8.5a5
  3. cd into the unix directory:

    $ cd unix
  4. Configure the build system:

    $ ./configure –with-tcl=../../tcl8.5a5/unix –prefix=/opt –enable-gcc
    ...
    config.status: creating Makefile
    config.status: creating dltest/Makefile
    config.status: creating tKConfig.sh
  5. The argument—with-tcl=../../tcl8.5a5/unix tells the Tk configure script where to find tclConfig.sh, which Tk needs in order to build and run properly. This is the reason that you built Tcl first. The other two arguments have the same meaning as they did for the Tcl installation.

  6. Build it:

    $ make
    ...
    gcc -pipe -O2    -Wl,—export-dynamic  tkAppInit.o -L/home/kurt/tclbook/tk8.5a5/
    unix -ltk8.5
    
                    -L/home/kurt/tclbook/tcl8.5a5/unix -ltcl8.5  -lX11  -ldl  -lieee
     -lm  -Wl,-rpath,/opt/lib -o wish
  7. While the build proceeds, fetch your third cup of coffee.

  8. Run the test suite:

    $ make test
    ...
     1       userInteraction
     288     win
     51      winSend

    While the test suite runs (it takes longer for Tk than for Tcl), your screen will seem to have been taken over by an invisible user. If it’s too disturbing to watch, get another cup of coffee. Or perhaps you should have a beer to counteract all the coffee you’ve been drinking. It isn’t uncommon to see tests skipped, so you can probably disregard messages about skipped tests. However, if you see more than a few failed tests, and you are motivated, you might consider reporting them to the Tcl developers using the Tk bug tracker at sourceforge.net/tracker/?group_id=12997&atid=112997&func=add.

  9. Assuming the test passed, install the Tk binaries and libraries. This step requires root access. On my system, I use sudo. Use the method that suits you for becoming root on your system:

    $ sudo make install
    Installing and cross-linking top-level (.1) docs
    Installing and cross-linking C API (.3) docs
    Installing and cross-linking command (.n) docs

That’s it. Tcl and Tk are installed.

This chapter answered the five most burning questions of the day: “What is Tcl?” “What is Tk?” “What makes Tcl and Tk different?” “Why should I use Tcl and Tk?” and “How do I get Tcl and Tk?” The next chapter starts answering the question, “How do I use Tcl and Tk?”

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset