Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re: Checkbutton in a loop

by Eliya (Vicar)
on Apr 29, 2012 at 08:37 UTC ( #967918=note: print w/ replies, xml ) Need Help??


in reply to Checkbutton in a loop

What do you expect $j to be when the callback function gets called?  You have to somehow pass it as an argument to the routine.  There are two ways to pass the value:

Either specify an array(ref) to the -command option

... for my $i (0...$#a) { $f->Checkbutton(-text => $a[$i], -command => [ \&fun, $i ] )->pack +(); } MainLoop; sub fun { my $j = shift; print $a[$j]; }

Or use a closure

... for my $i (0...$#a) { $f->Checkbutton(-text => $a[$i], -command => sub { fun($i) } )->pa +ck(); } ...


Comment on Re: Checkbutton in a loop
Select or Download Code
Re^2: Checkbutton in a loop
by Anonymous Monk on Apr 29, 2012 at 09:27 UTC

    There is a third option, don't pass it any arguments

    use Tk; $mw = tkinit; for(1..4){ $mw->Checkbutton( -text => qq/check it $_/, -command => \&f, ) ->pack; } MainLoop; sub f { my $b = $Tk::event->W; warn join q/ /, $b->{Value}, $b->cget(q/-text/); } __END__ 1 check it 3 at - line 14. 0 check it 3 at - line 14. 1 check it 3 at - line 14. 0 check it 3 at - line 14. 1 check it 3 at - line 14. 0 check it 3 at - line 14. 1 check it 3 at - line 14. 0 check it 3 at - line 14.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://967918]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (10)
As of 2014-09-17 20:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (98 votes), past polls