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(); } ...

Replies are listed 'Best First'.
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.