Tk Sets The Standard by Cameron Laird and Kathryn Soraiz

Title
TkSets The Standard
Author
Cameron Laird
Author
Kathryn Soraiz
When
2001-04-13
At
itworld

Article Content

Tk is similar to Qt and Motif, the first two toolkits reviewed in this series, in that it is a library coded in C that implements a collection of widgets. However, unlike Qt and Motif, Tk is known by most programmers through its binding to the Tcl scripting language, rather than through C itself.

It is widely believed that Tk is slow because it is used with a scripting language and scripting languages don't perform like C or assembly. This is simply not true -- Tk is comparable in speed to other leading toolkits. In fact, it's considerably zippier than Java's Abstract Windowing Toolkit (AWT). Moreover, because Tk's design intentionally emphasizes easy use for common design situations, Tk is ripe for optimization. As a result, many Tcl/Tk applications are faster than their Motif-based counterparts.

John Ousterhout, a professor at the University of California at Berkeley, created Tcl and Tk in the late 1980s; since then, users and developers of Tcl and Tk have generally belonged to the same demographic. The toolkits are not identical, though. Many Tk programmers base their work on C, Perl, Python, Ruby, Lua, or Scheme. Two recent, well-received books on Tk development are aimed at Perl and Python programmers, rather than those working with Tcl.

So it can be advantageous to understand the roots Tk shares with Tcl, but it's not necessary to use one with the other. Some Tk characteristics are bound to Tcl; some are more generally available.

Portability sets Tk apart from other toolkits -- it is more portable than any other contemporary GUI toolkit, even AWT. Good Tk implementations are available for all Unixes, as well as for Windows, Mac OS, OpenVMS, and other more specialized operating systems.

That dominance seems likely to change: Java Virtual Machines continue to improve, and Qt and wxWindows seem to be on course to release Mac OS versions. Tk's Mac OS distribution has appeared to weaken over the last year. Few developers have contributed to its maintenance, and despite frequent inquiries about a Tk for the Palm OS, one doesn't seem likely to emerge soon.

On the other hand, Tk is currently undergoing its most significant change since it was first ported to the Mac OS in the mid-'90s. The TkGS team, led by Frédéric Bonnet, is reworking Tk's internal design to improve performance and maintainability. It is widely anticipated that once this is completed, Tk ports to Microwindows or Nanox will be quick and nimble. And besides the complete TkGS rewrite, one group is investigating the possibility of a rapid port to Microwindows or Nanox from the current code base.

Tk, clearly in the lead right now with regards to portability, is also a favorite among developers striving for platform neutrality.

Expressiveness and wise defaults

Another benefit of Tk is its conciseness. The classic minimal Tk application is indeed tiny:

pack [button .mybutton -text Bye-bye -command exit]

This is a small but complete program in Tcl/Tk that puts a button on the screen and exits when the button is pushed, with proper behavior for iconifying, clicking, and other GUI conventions.

This economy of expression has two aspects. One is its realization in a scripted binding. All GUI toolkits look powerful in a good binding with a scripting language. Typical lessons in Motif programming require explanation of compilation, .h headers, string representations, and memory management before a beginner even attempts to create a working application. This mainly reflects the difference between C's tedium and other scripting languages.

The second aspect is that even apart from its usual exposure through a scripting language, Tk is remarkably concise. Ousterhout deliberately defined Tk to behave reasonably with default values. Tk programmers often write skeletal implementations and fill in details as requirements emerge. Tk encourages this style more than any other toolkit. This complements the scripting language bindings nicely, because these languages are more flexible than C, which has defined sequences of formal parameters. Scripting languages are comfortable with variable numbers of arguments, default arguments, and arguments of variable type. Tk uses this freedom wisely.

One testimony to the power of this incrementalism is the number of programmers who use Tk by accident. We hear many anecdotes of developers who choose Tk as a quick prototyping tool, then discover they're able to complete a full-blown application by refinement of the prototype.

Getting the most from Tk

Effective Tk programming depends on several specific technical concepts:

  • The power of the text and canvas widgets
  • Geometry management
  • Event binding

Tk has a modest complement of widgets. The core Tk distribution lacks widgets for tree display, SpinBox, ComboBox, graphing, and several others that are now commonplace. One frequent complaint about Tk is that it has "become rather lackluster in the age in terms of core features," according to Jeffrey Hobbs of Ajuba Solutions. However, the Tk text and canvas are so powerful, and Tk so extensible, that developers have lived without new features by relying on free extensions.

text and canvas powerhouses

text's capabilities lie somewhere between those of Java's TextArea and JEditorPane. Text embeds both a compact visual editor and an HTMLv2 display engine, and defines sophisticated tag programming, making visual effects easy. text's full Unicode capabilities helped internationalize it a couple of years ago with the 8.1 release.

It's important to distinguish between different notions of "graphical" when discussing GUIs. One usage implies form-based GUI programming and expresses the difference between old curses or IBM 3270-based applications and typical Web browsers. Browsers depend on cursor movement and selection by clicking. Tk's text and related widgets such as button and label suffice for most form-based GUI programming.

Applications in geographic information systems, electronic design automation, and complex visualization require a second level of graphics to display and manage arbitrary drawings such as maps, engineering diagrams, and images. Many successful programmers work only on form-based office automation tasks. However, Tk's canvas can help those with more general needs.

canvas is like text in that it embeds much functionality, unified by analogous programmability in terms of tags and configuration attributes. Tk is the established basis for successful commercial GUI applications, many of which have stringent requirements for scale and performance. One is Red Hat's Source-Navigator IDE (integrated development environment), used with all programming languages. Red Hat engineer Mo DeJong recently wrote, "We are really pushing to make it the default IDE for Linux."

Geometry

Tk's fans also laud the toolkit for its geometry management. Geometry is the positioning of widgets on the visual screen. Windows's Visual Basic is reputedly easy for beginners because of its IDE's facility for dragging and dropping widgets into a form. However, due to its inflexibility in managing windows of variable sizes, this approach is severely limited in building professional applications.

Tk, by contrast, offers a variety of geometry managers, most of which can intelligently handle window resizing. It's typical in Tk to code such elements as:

pack $save_button $cancel_button $help_button \
    -side left -fill both -expand yes

This places three buttons in a sequence from left to right. Tk makes sure that the buttons are symmetrical and that they adjust properly to size changes.

Tk's geometry management is so widely admired, one common complaint heard about Java is that it still doesn't do geometry well, even though it's had at least five years to learn from Tk.

Events

Event handling distinguishes between different GUI toolkits. The programming model for all GUI systems has them wait for, receive, and communicate events to small pieces of code, or callbacks. Tk's event handling resembles its other programming constructs: its concisely expressed default actions are adequate for many situations, and more flexibility is available if necessary. In the one-line program near the top of this article, the -command exit phrase says, "When someone pushes the button, perform the Tcl procedure named 'exit.'" This command callback can hold arbitrarily complex instructions. A PerlTk program might read:

$window->Button(-command => sub {
    sub1();
    sub2();
    # Do still other things.
    subn();
})->pack

The flexibility is dual, which means one can associate arbitrary callbacks to standard events, as well as precisely manage the events an application recognizes. Tk's bind command can program the Enter key to duplicate an on-screen button click:

bind $my_button <Key-Return> "$my_button invoke"

This precise, programmatic control gives Tk a great advantage in constructing highly responsive GUIs. Tk makes it easy to "gray out" buttons for actions that temporarily don't make sense, program hot spots on a screen, and generally implement what Bell Labs researcher Brian Kernighan calls intelligent GUIs, which are sensitive to context.

State of the toolkit 2000

Hobbs's own history with Tk is typical. "I was originally a C/Motif programmer. Once I learned Tk, I never did another project in Motif," he said. In fact, one Tcl insider claims to have once overheard Tim O'Reilly of O'Reilly & Associates (ORA) saying that Tk's introduction cut the sales of ORA Motif manuals.

The future of Tk is uncertain, though. Recent generations of programmers, based in Windows and Linux, tend to regard Tk applications as old-fashioned in appearance. The absence of an officially supported drag-and-drop visual builder for Tk is a barrier for many. Tk's commitment to Mac OS support seems tentative, and other toolkits are improving their portability. Where does this leave Tk in the year 2000?

Hobbs said:

Tk has a rich set of extensions that expand the widget set considerably ... Many of the complaints that Tk hasn't aged well are fairly near-sighted, because they never take account of the wealth of widget extensions available. Hopefully the new sumo Tcl distribution will finally address those concerns, along with fostering a more open development community that is interested in working with a larger Tcl distribution.

So the Tcl development community is reorganizing itself to accelerate release cycles. Moreover, Hobbs and his colleagues are repackaging Tcl distributions to make popular extensions more accessible to nonexperts. "8.4 should be the first distribution that has a coexisting 'batteries included' release," said Hobbs. "Major extensions that work with TEA (Tcl Extension Architecture) would be gathered together and all released."

Those aren't the only structural changes. Tk's stewards are working to capture more of the open source buzz competing toolkits now receive. Consolidation of the internationalization and performance benefits of versions 8.0 to 8.2 has already led to opportunities for specific new features. Hobbs reported, "More recently, the core of Tk incorporated popular paths that enhanced the existing widget set. The entry widget can validate input easier than before, the already feature-rich canvas receives even more features, the list box gets individualized color, and the text widget can now have hidden text fields." The official 8.4 release is scheduled to include a new megawidget system "to make Tcl-level graphical extensions easier to create than ever before."

Hobbs concluded, "Tk is a simple and elegant UI toolkit that works across platforms without any code changes. Development time for a Tk app is significantly less than for the equivalent Java or C++ UI toolkit app."

Broader context

Tk can certainly hold its own with other GUI toolkits. Its variety of available language bindings means almost anyone curious about Tk can quickly find a version in a familiar language. It only takes a few minutes to begin producing meaningful applications, and there are plenty of books and tutorials to help.

However, there's a broader context that, at least temporarily, falsifies some of what we've already written -- for the last couple of years, our true toolkit of choice was not Tk, but HTML. As Tim O'Reilly told us about the aforementioned incident regarding Motif book sales, "I don't remember saying anything of the sort ... What eventually wounded both Tk and Motif, perhaps fatally, was the rise of the Web, which took the frontier of application development away from the desktop and put it instead in the browser-server interaction."

The current Silicon Valley rush to Webification is as silly as the aversion to the same architecture displayed by large corporations just a few years ago. Plenty of applications require the rich feature set of a toolkit such as Tk.

There's no doubt, though, that fashion can dominate computing for long stretches. One can easily conceive of a world that turns its back on Tk. The toolkit's usage might become limited to a core of developers and administrators who realize its indispensability for extremely rapid production of portable, intelligent, fully internationalized, visually well-behaved GUI applications.

There are at least a couple more wrinkles in this speculation. O'Reilly is one of many commentators to foresee open source Mozilla as the basis for the standardized toolkit of the future. This might make Tk more popular than ever, because Steve Ball of Zveno is working with TkGecko to create a Tk extension that allows the NewLayout rendering engine to be embedded in a Tk application as a Tk widget. Ball hopes this new widget will be as configurable as other Tk widgets, with all configuration options able to be queried and changed at runtime.

There are several interesting client-side Tk Web stories. The Tk plug-in is a module compatible with Microsoft's Internet Explorer and Netscape Navigator, which allows Web presentations to be scripted in Tcl, as they are currently done in JavaScript. The plug-in, a remarkably capable extension, has proved itself in several production systems. Although its maintenance was largely dormant for a couple of years, Ajuba is now making it compatible with the latest browser and Tk versions.

Summary

Tk's prospects involve so many free variables that the toolkit's future defies predictions. What's certain is that Tk's fans find the toolkit exceptionally useful right now, and that new widgets, books, and language bindings are making it easier for a newcomer to learn and for a mature programmer to use expertly.

Resources