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

Is there a way to set the default value for an Optionbox? I'm using it to select a vendor and there are too many to fit on the screen using Tk::Optionmenu.

$selectVendor = $newTop->Optionbox(-text=>'Vendor', -command => \&select_vendor, -variable=> \$vsel, -font=>$variableFont, -options=> [@options], -rows =>15, )->pack(-side=>'left'); $vsel = "Amazon"; $selectVendor->configure(-variable => \$vsel);

Where 'Amazon' is the third entry in the @options list.

Replies are listed 'Best First'.
Re: Tk::Optionbox default
by thundergnat (Deacon) on Apr 10, 2015 at 17:00 UTC

    The documentation seems to imply that the variable is tied somehow so changes will be automatically applied, but I don't see code to do that anywhere. It looks like if you replace your line

    $selectVendor->configure(-variable => \$vsel);

    with

    $selectVendor->set_option( $vsel, $vsel, $vsel );

    it seems like it does what I think you want.

    See test code below:
    use warnings; use strict; use Tk; use Tk::Optionbox; my $newTop = MainWindow->new; my $vsel; my @options = ( qw/ This That Amazon Th'other too many to fit on the s +creen/); my $selectVendor = $newTop->Optionbox(-text=>'Vendor', -command => \&sayit, -variable=> \$vsel, # -font=>$variableFont, -options=> [@options], -rows =>15, )->pack(-side=>'left'); $vsel = 'Amazon'; $selectVendor->set_option( $vsel, $vsel, $vsel ); MainLoop; sub sayit { print $_[0], "\n"; }
Re: Tk::Optionbox default
by golux (Chaplain) on Apr 10, 2015 at 17:40 UTC
    Hi jinnicky,

    Another alternative which seems to work is to change -variable to -textvar:

    #!/usr/bin/perl -w use strict; use warnings; use feature qw{ say }; use Tk; use Tk::Optionbox; my $default_vsel = "Amazon"; my @options = ( 'option1', 'option2', $default_vsel, 'option4', ); my $mw = Tk::MainWindow->new(-title => 'Tk::Optionbox exampl +e'); my $vsel = $default_vsel; my $variableFont = 'Arial'; my $newTop = $mw->Frame->pack(-expand => 1, -fill => 'x'); my $selectVendor = $newTop->Optionbox( -command => \&select_vendor, -textvar => \$vsel, -font => $variableFont, -options => [@options], -rows => 15, )->pack(-side=>'left'); Tk->MainLoop; sub select_vendor { my $vendor = shift; say "Vendor is '$vendor'"; }
    say  substr+lc crypt(qw $i3 SI$),4,5
      Thanks thundergnat and golux Both solutions work.