Option Menus

An option menu is a simple widget with a label and an indicator. Clicking the indicator posts a menu of selections from which we can choose any single value, which is then displayed in the label. An option menu has an associated Perl variable that keeps the current option value and may also have a -command callback that is invoked after the new option value is stored in the variable.

Perl/Tk has two option menu widgets: Tk::Optionmenu from the standard distribution and a native option menu that almost no one is aware of but that you will see shortly. Each has its pros and cons, so pick one based on the job at hand. Both option menus are based on a Menubutton widget, which posts its menu items when pressed.

Tk::Optionmenu

If we want to select a color from a small set of colors, we could use an Optionmenu like that shown in Figure 12-8. The operative word is small, because an Optionmenu’s menu is limited to a single column. The -options option expects a reference to a list of options, which may be string values and/or array references of the form ['label' => 'value']. The 'label' is what’s displayed in the menu, and the 'value' is stored in the variable. The -command option is a standard Perl/Tk callback. When the callback is invoked, the value of the option menu is appended to the callback argument list.

my $palette; my @colors = qw/Black red4 DarkGreen NavyBlue gray75 Red Green Blue gray50 Yellow Cyan Magenta White Brown DarkSeaGreen DarkViolet/; my $om = $mw->Optionmenu( ...

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