Chapter 21. Perl/Tk

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.

A simple Perl/Tk program

Figure 21-1. A simple Perl/Tk program

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 ...

Get Perl in a Nutshell, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.