Making Menus with wxPerl
by Roberto Alamos
|
Pages: 1, 2, 3, 4, 5, 6
A Quick Example
Instead of wading through several pages of explanation before the first example, here is a short example that serves as a summary of this article. Note that I have divided it in two parts. Add this code to the base code in the WxPerlComExampleFrame constructor:
# Create menus
my $firstmenu = Wx::Menu->new();
$firstmenu->Append($id[0], "Normal Item");
$firstmenu->AppendCheckItem($id[1], "Check Item");
$firstmenu->AppendSeparator();
$firstmenu->AppendRadioItem($id[2], "Radio Item");
my $secmenu = Wx::Menu->new();
$secmenu->Append(wxID_EXIT, "Exit\tCtrl+X");
# Create menu bar
my $menubar = Wx::MenuBar->new();
$menubar->Append($firstmenu, "First Menu");
$menubar->Append($secmenu, "Exit Menu");
# Attach menubar to the window
$self->SetMenuBar($menubar);
$self->SetAutoLayout(1);
# Handle events only for Exit and Normal item
EVT_MENU( $self, $id[0], \&ShowDialog );
EVT_MENU( $self, wxID_EXIT, sub {$_[0]->Close(1)} );
Insert the following code into the base code at the line ### PUT SUBROUTINES HERE ###.
use Wx qw(wxOK wxCENTRE);
# The following subroutine will be called when you click in the normal item
sub ShowDialog {
my($self, $event) = @_;
Wx::MessageBox( "This is a dialog",
"Wx::MessageBox example",
wxOK|wxCENTRE,
$self
);
}
Run this example to see something like Figures 1 and 2.

Figure 1. A menu with complex sub-items

Figure 2. A menu with a single sub-item
Programming Menus
To add a menu to your wxPerl application, you must know how to use two Perl modules that come with WxPerl: Wx::MenuBar and Wx::Menu. Wx::MenuBar creates and manages the bar that contains menus created with Wx::Menu. There is also a third module involved: Wx::MenuItem. This module, as its name implies, creates and manages menu items. You usually don't need to use it, because almost all of the operations you need for a menu item are available through Wx::Menu methods.

