11.3. Complete Menubutton Examples

Menus are a more complicated widget than we've seen before because you don't always add items to them the same way. Sometimes you can use the simple -menuitems option, and other times you'll want to add to them dynamically. This section contains some full-length Perl scripts that create some useful menus.

11.3.1. Creating a Menubar

Here is the code that was used to create the window and menubar in Figure 11.4:

#!/usr/bin/perl -w
use Tk;
my $mw = MainWindow->new;
$mw->title("Menubutton");

$mw->Button(-text => "Exit",
            -command => sub { exit; })->pack(-side => "bottom");

my $f = $mw->Frame(-relief => 'ridge', -borderwidth => 2);
$f->pack(-side => 'top', -anchor => 'n', -expand => 1, -fill => 'x');

foreach (qw/File Edit Options Help/) {
  push (@menus, $f->Menubutton(-text => $_));
}

$menus[3]->pack(-side => 'right');
$menus[0]->pack(-side => 'left');
$menus[1]->pack(-side => 'left');
$menus[2]->pack(-side => 'left');

MainLoop;

First a frame was created across the top of the window and packed so it will resize itself dynamically when the window gets larger or smaller. Then the menubuttons were created and packed into the frame. Each of the menus has no items. We'll leave that as an exercise for the reader.

11.3.2. Dynamic Document List

In certain cases, you'll want to add and remove items from a menu dynamically. Many applications remember which documents you've most recently opened and keep them attached to the File menu for easier access later. ...

Get Learning Perl/Tk 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.