Perl/Tk - Writing Tk applications in Perl 5

返回


NAME
Perl/Tk - Writing Tk applications in Perl 5

DESCRIPTION
This document is for beginners. It assumes you know some Perl, and have
it and Tk running. If you are *not* currently reading this document
courtesy of the widget demonstration program, please be sure to run
widget, as it will show you the various widget types supported by Tk and
how to use them. widget should be installed in your default path, so
type *widget* at a command prompt.

Here are links to other novice tutorials:

http://www.lehigh.edu/~sol0/ptk/tpj1.html
http://www.lehigh.edu/~sol0/ptk/perlmonth01/pm1.html

*Mastering Perl/Tk* is the definitive book on Perl/Tk:

http://www.oreilly.com/catalog/mastperltk

Some Background
Tk GUI programming is event-driven. (This may already be familiar to
you.) In event-driven programs, the main GUI loop is outside of the user
program and inside the GUI library. This loop - initiated by calling
MainLoop - watches all events of interest and activates the correct
handler procedures to handle these events. Some of these handler
procedures may be user-supplied; others will be part of the library.

For a programmer, this means that you're not watching what is happening;
instead, you are requested by the toolkit to perform actions whenever
necessary. So, you're not watching for 'raise window / close window /
redraw window' requests, but you tell the toolkit which routine will
handle such cases, and the toolkit will call the procedures when
required. These procedures are known as *callbacks*, and some of them
you write yourself.

First Requirements
Perl programs that use Tk need to include "use Tk". A program should
also use "use strict" and the -w switch to ensure the program is working
without common errors.

Any Perl/Tk application starts by creating the Tk MainWindow. You then
create items inside the MainWindow, and/or create new windows called
Toplevels that also contain child items, before starting the MainLoop,
which is the last logical statment in your program. You can also create
more items and windows while you're running, using callbacks. Items are
only shown on the display after they have been arranged by a *geometry
manager* like pack; more information on this later. MainLoop starts the
GUI and handle all events. That's all there is to it!. A trivial
one-window example is shown below:

#!/usr/bin/perl -w
use Tk;
use strict;

my $mw = MainWindow->new;
$mw->Label(-text => 'Hello, world!')->pack;
$mw->Button(
-text => 'Quit',
-command => sub { exit },
)->pack;
MainLoop;

Please run this example. It shows you two widget types, a Label and a
Button, and how they are packed. When clicked, the

返回