my $label = $mw->Button( [ option => value ] );Two of the more common options are
#!perl # file button.pl use Tk; use strict; use warnings; my $mw = MainWindow->new; $mw->title('Button'); my $hello = $mw->Button(-text => 'Greetings!', -command => \&print_hello); my $exit = $mw->Button(-text => 'Exit', -command => [$mw => 'destroy']); $hello->pack(-side=>'left'); $exit->pack(-side => 'right'); MainLoop; sub print_hello { print "Hello, earthling ....\n"; }which appears in the figure below.
The first button, $hello, invokes the print_hello subroutine when pressed, which simply prints out a message to the terminal used to launch the script. The second button, $exit, is used to destroy the main window and to begin executing any code after the MainLoop statement. We will see some more examples of the use of buttons in the sections that follow.
It is also possible to use an image on a button, rather than a text label. GIF and PPM/PGM formats are supported, as well as the JPEG format through the Tk::JPEG module. To do this, first create an image pointer as
my $img = $mw->Photo(-file => 'filename');and then create the button as
my $button = $mw->Button(-image => $img);For example, the script
#!perl # file button1.pl use Tk; use strict; use warnings; my $mw = MainWindow->new; $mw->title('Button'); my $img = $mw->Photo(-file => 'dino.gif'); my $hello = $mw->Button(-image => $img, -command => \&print_hello); my $exit = $mw->Button(-text => 'Exit', -command => [$mw => 'destroy']); $hello->pack(-side=>'left'); $exit->pack(-side => 'right'); MainLoop; sub print_hello { print "Hello, earthling ....\n"; }results in the following:
Alternatively, you can specify a bitmap to use, as in
my $button = $mw->Button( -bitmap => bitmap);Several bitmaps available in the standard Tk distribution - error, gray12, gray25, gray50, gray75, hourglass, info, questhead, question, and warning. As an example,
#!perl # file button2.pl use Tk; use strict; use warnings; my $mw = MainWindow->new; $mw->title('Button'); my $hello = $mw->Button(-bitmap => 'questhead', -command => \&print_hello); my $exit = $mw->Button(-text => 'Exit', -command => [$mw => 'destroy']); $hello->pack(-side=>'left'); $exit->pack(-side => 'right'); MainLoop; sub print_hello { print "Hello, earthling ....\n"; }results in the following
Randy Kobes 2003-11-17