7.1. Creating and Filling a Listbox

To create a listbox widget, use the Listbox method on the parent of the listbox:

$lb = $parent->Listbox( [ options ...])->pack;

The Listbox method returns a reference to the listbox that has been created. You can now use this reference to configure the listbox, insert items into the listbox, and so on. The most common thing to do after creating a listbox is to use the insert method to insert items into it:

$lb->insert('end', @listbox_items);
# or...
$lb->insert('end', $item1, $item2, $item3);

The insert method takes an index value as the first argument; the rest of the arguments will be considered items to be put into the listbox. Listbox indexes are similar to the entry widget indexes except they refer to lines instead of individual characters.

We could use a listbox instead of radiobuttons to select our window background color (see Chapter 4, for the radiobutton example). The listbox code looks like this:

$lb = $mw->Listbox(-selectmode => "single")->pack();
$lb->insert('end', qw/red yellow green blue grey/);
$lb->bind('<Button-1>', 
          sub { $lb->configure(-background => 
                             $lb->get($lb->curselection()) );
              });

The -selectmode option limits the number of selections to one. We insert some colors to choose from. There is no -command option for a listbox, so we use bind (see Chapter 14) to have something happen when the user clicks on an item with the left mouse button. Using the listbox methods get and curselection, we determine which item the user ...

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.