kgb_321 has asked for the wisdom of the Perl Monks concerning the following question:

How do I make Button-3 act like Button-1 in a listbox and then go on to do something. $lb->bind(<Button-3>, "I want to get the item closest to the cursor and assign a $variable to it" );

Replies are listed 'Best First'.
Re: Tk listbox item select
by rcseege (Pilgrim) on Mar 22, 2005 at 02:41 UTC
    For a simple case (where you are only allow a single item to be selected at a time, you could try something like this:
    use Tk; use strict; use warnings; my $value; my $mw = MainWindow->new; my $entry = $mw->Entry( -state => 'readonly', -textvariable => \$value )->pack; my $lb = $mw->Listbox( -height => 0 )->pack; $lb->insert('end', qw/one two three four five six/); $lb->bind('<ButtonPress-3>', [\&setItem, \$value, Ev('@')]); sub setItem { my ($lb, $valSR, $xy) = @_; $lb->selectionClear(0, 'end'); my $index = $lb->index($xy); if (defined($index)) { $lb->selectionSet($index); $$valSR = $lb->get($index); } } MainLoop;
    A slight variation of this:
    use Tk; use strict; use warnings; my $value; my $mw = MainWindow->new; my $entry = $mw->Entry( -state => 'readonly', -textvariable => \$value )->pack; my $lb = $mw->Listbox( -height => 0 )->pack; $lb->insert('end', qw/one two three four five six/); $lb->bind('<ButtonPress-3>', [\&setItem, \$value]); sub setItem { my ($lb, $valSR) = @_; my $xy = $lb->XEvent->xy; $lb->selectionClear(0, 'end'); my $index = $lb->index($xy); if (defined($index)) { $lb->selectionSet($index); $$valSR = $lb->get($index); } } MainLoop;
    Note the modification to the <Button-3> bind, and the first two lines of the setItem sub. I used to prefer the latter rather than the former, because I thought that it was easier to read, but I've since changed my mind -- especially when coding a Tk module, because I find the former is easier to unit-test reliably across different platforms. Your mileage may vary...