Skip to Main Content
Perl in a Nutshell, 2nd Edition
book

Perl in a Nutshell, 2nd Edition

by Nathan Patwardhan, Ellen Siever, Stephen Spainhour
June 2002
Beginner content levelBeginner
759 pages
80h 42m
English
O'Reilly Media, Inc.
Content preview from Perl in a Nutshell, 2nd Edition

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

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Perl by Example, Fourth Edition

Perl by Example, Fourth Edition

Ellie Quigley
Perl Cookbook, 2nd Edition

Perl Cookbook, 2nd Edition

Tom Christiansen, Nathan Torkington
Perl in a Nutshell

Perl in a Nutshell

Nathan Patwardhan, Ellen Siever, Stephen Spainhour
Learning Perl, 7th Edition

Learning Perl, 7th Edition

Randal L. Schwartz, brian d foy, Tom Phoenix

Publisher Resources

ISBN: 0596002416Errata Page