GUI Construction With Perl

Dr. Dobb's Journal January 2001

Yes, you can build GUIs with Perl

By Cameron Laird

Cameron works for Phaseit, a consulting firm. He can be contacted at claird@ neosoft.com.
Installing Perl/Tk for Windows

Contrary to popular belief, it is possible to build graphical user interface (GUI) applications with Perl. In fact, it's likely that you should use Perl for at least part of your GUI work. But before surveying the possibilities, let me first clear away several misperceptions about Perl:

With those distractions out of the way, I'll focus in this article on how straightforward it is to start using Perl to build GUIs, then present some options you have when relying on Perl for GUI development.

Your First Perlish GUI

Starting from scratch, you should expect to be building your own small GUI programs with Perl in under an hour. The minimal sequence is:

1. For Windows, follow the directions in the accompanying text box entitled "Installing Perl/Tk for Windows." For UNIX, download a recent Perl source distribution, generate and install it, then repeat the process for the Perl/Tk sources. The references at the end of this article suggest where you can find these packages within the Comprehensive Perl Archive Network (http://www.cpan.org/).

2. Use a text editor to prepare a source file named "first.ptk" that contains:

use Tk;

my $main = MainWindow->new;

$main->Button(-text => "Push me",-command => sub {exit})->pack;

MainLoop;

3. Launch the application by typing perl first.ptk at the command line. Up pops a small but live window that looks like Figure 1.

That's all it takes to start Perl-based GUI building. (And many of you will even be able to skip or shortcut the first step, because your operating system includes Perl and possibly Perl/Tk.)

The first.ptk program includes the basic elements most GUI toolkits and languages employ to specify widgets, geometric layout of created widgets, and attachment of executable routines to widgets. In this case, the first line, use Tk, alerts Perl to take advantage of the Tk library installed in Step 1, while the next line is a boilerplate to create a working main window in which to display the application.

The real content of this tiny application is in the Button() call. Perl/Tk creates widgets by invoking methods armed with attribute information. You define your example button with text whose value is Push me. While the button has dozens of other attributes — including background color, font, and cursor image — you can let them all take default values. One of the charms of the Perl/Tk system is how well defaults turn out in many practical cases. Other GUI systems demand that much of this information be specified explicitly. Perl, in contrast, glorifies brevity.

Why Perl/Tk is Good

Other articles in this issue make the point that such high-level and succinct languages as Perl accelerate development, simply because there's less to think about and less to type. The computer does more of the work, and makes better use of your time. Tkweb, for example, is a functional web browser written in less than a hundred lines of Perl/Tk code.

Moreover, highly expressive languages improve quality. Code that doesn't need to be written can't suffer the accidents of mistyping or otherwise go wrong. Anything that does go wrong in a powerful language tends to be dramatic and correspondingly easy to identify and correct. You spend less time with mere contingencies and concentrate on the essentials.

Also, Perl/Tk is scripted, in the sense that the Perl language processor executes statements immediately, without an operationally separate compilation phase. It can be hard to appreciate the benefit of this difference without personal experience. If you're accustomed to modern IDEs with such languages as C++ or Java, for example, you might justly feel that the IDE's automation and incremental compilation essentially gives you immediate execution. As sensible as that seems in the abstract, the reality of working with a true interpreter such as Perl is much livelier (and more fun).

This difference applies particularly in the case of GUI applications. Large GUIs always seem to involve lots of polishing to perfect them. Think for a moment about Java and its reputation for scalability. When it comes to GUI development, I find the opposite is often true — Java GUI development goes quickly in the beginning, then becomes exceptionally tedious as small source-code changes require minutes of recompilation. With Perl/Tk, I cycle through editing changes and relaunch even large applications within seconds on the older, slower hardware that I tend to accumulate.

True Interactivity

Perl/Tk offers yet another level of interactivity that can be enormously convenient — an interactive shell. An interactive shell interprets not just statements from a text file considered as scripts, but lines as you enter them in real time.

Assume you've installed Perl/Tk and have launched the ptksh application that comes with it. You'll see a new console with the ptksh prompt. This console lets you type in any Perl/Tk statements and tune your GUI while it's running.

If you start a ptksh session with:

$my_button = $mw->Button(-text => "Push me");

$my_button->pack;

you'll see a button on the screen that looks identical to the one first.ptk supplies. Without leaving the ptksh console, enter:

$my_button->configure(-text => "Push me harder", -foreground => red);

The button's label and color change immediately. What makes this powerful is that you can work with the same source code and applications either as batched scripts, with the usual Perl processor, or interactively, in the ptksh console. This flexibility multiplies productivity.

Growing Bigger Perl GUIs

Recall that the sample first.ptk program created its button with not just a label, but also an action — the sub {exit} routine. If you push the button while the application is running, the program performs this action and exits.

However, the action can be arbitrarily complex. You can use the full power of Perl so that the button push starts a three hour data-mining operation, sends a signal to turn on the outside lights at your house, or delivers the latest weather maps to 100 subscribers of an e-mail service.

The final element of that same Perl statement is the ...->pack method invocation. pack handles geometric layout. Without any arguments, it simply manages the button in a sensible way, wrapping the MainWindow around it snugly.

Compared to Other Toolkits

Most programmers still use languages such as C, C++, or Java, with such toolkits as Motif and MFC. To create the same single pushbutton with Motif and C, I have to write at least three times as much code and maintain a project or makefile or other generation sequence.

Many developers make that sacrifice because they think they gain run-time performance or a more professional appearance with compiled languages. This is rarely true. Modern Perl/Tk is fast — frequently even faster than Motif, MFC, or Java for operations significant in real applications.

Perl/Tk can also manage quite large applications, simply by elaborating the elements already present in first.ptk — widget specification, geometric layout, and association of on-screen events to executable actions.

Alternative GUI Toolkits

Keep in mind that while Perl/Tk is the maturest binding of Perl and a GUI toolkit (Nick Ing-Simmons first released it in 1994, and it's prospered well enough to support a Usenet newsgroup, comp.lang .perl.tk, as well as several books), it isn't your only choice. For a different visual appearance, base widget set, or compatibility with organizational standards, you can also use Win32, Qt, wxWindows, and GTK+ toolkits. Qt, wxWindows, and GTK+ are largely portable between Windows and UNIX, with variable prospects for MacOS availability. All are generally regarded as having more modern looks than Tk. Trolltech AS provides high-quality professional support for Qt, and the KDE desktop environment relies on Qt as its GUI toolkit. GNOME is the KDE rival that several vendors support; GTK+ codes the visual components of GNOME.

PerlQt was at Version 2.105 in March 2000. At that point, though, it was only available for UNIX.

Perl bindings to wxWindows have not been maintained energetically. While it would take only a single person to change that situation, at this point it appears that wxPerl is mostly for hobbyists.

The GTK+ binding for Perl appears to be developing quite rapidly. By the time you are reading this, it seems likely that nearly complete Perl-plus-GTK+ kits will be as easy to install and use as Perl/Tk.

How do you decide between toolkits? You'll probably choose on the basis of social factors — which toolkits your buddies use, whether you come across a pertinent reference on the shelf of your local bookstore, or whether you like the prose style of the maintainer of the toolkit's binding.

Making a decision that way is okay. GUI toolkits have converged quite a bit over the last few years, so that their technical functionalities are comparable. Whichever one you choose, you'll deal with roughly the same programming concepts and abstract widget sets. While the programming interface for Qt, for example, is generally recognized as more mature and polished than GTK+'s, their high-level models are quite similar.

Moreover, it's remarkably costly to make an informed technical decision. GUI programming involves a density of detail that goes beyond the scope of a single book, let alone an article such as this. Dozens of highly context-dependent factors might affect the usability of a particular binding for your projects:

The first.ptk program embeds several such potential complications. The earlier explanation refers to button pushes. This is a simplification. Properly speaking, the command action takes place at the time of button release. I also blurred the difference between interpretation and bytecode compilation at the beginning of this article. Distinctions such as these are crucial for some programmers and projects, and irrelevant for others.

For a deep comparison of specific factors, you need to ask an expert — or become one yourself. However, here are a few guidelines for comparing the bindings:

References

Information about the different toolkits is scattered around rather haphazardly. There's no comprehensive location that answers even a sizable fraction of the questions that a beginner is likely to have. The chief sites you should know are:

Conclusion

It's easy to start building GUI applications with Perl. Once you start, you can go far. If you do run into a problem or puzzle, there's probably someone who can help you with it.

DDJ