Perl/Tk is an extension for writing Perl programs with a graphical user interface (GUI) on both Unix and Windows 95/NT. Tk was originally developed as an extension to the Tcl language, for use with the X Window System on Unix. With its port to Perl, Tk gives Perl programmers the same control over the graphical desktop that Tcl programmers have taken for granted .
The Tk extension makes it easy to draw a window, put widgets into it (such as buttons, checkboxes, entry fields, menus, etc.), and have them perform certain actions based on user input. A simple “Hello World” program would look like this:
#!/usr/bin/perl -w use Tk; my $mw = MainWindow->new; $mw->Button(-text => "Hello World!", -command =>sub{exit})->pack; MainLoop;
When you run it, it would look like Figure 21-1.
Clicking on the Hello World button exits the program, and your window disappears.
Let’s walk through these few lines of code. After calling the Perl
interpreter, the program calls the Tk module. It then proceeds to build
a generic, standard window (MainWindow
) to act as a parent for any other
widgets you create. Line 4 of the program creates a button and displays
it using the pack
geometry manager.
It also gives the button something to do when pushed (in this case, exit
the program).
The last line tells the program to “go do it.” MainLoop
starts the event handler for the
graphical interface, and the program draws windows until it reaches the
MainLoop
statement. Everything up to
that point is preparation; until you reach the MainLoop
statement, the program simply
prepares its windows and defines what to do when certain events happen
(such as a mouse click on the Hello World! button). Nothing is drawn
until the MainLoop
statement is
reached.
18.221.232.187