in reply to Re: Perl/Tk : Trouble with commands and Checkbuttons
in thread Perl/Tk : Trouble with commands and Checkbuttons

This will not work, and will print 5,5 regardless which checkbutton you click. The issue is that you used the latest value of $x and $y, not the value at the time when the checkbutton is defined.

  • Comment on Re^2: Perl/Tk : Trouble with commands and Checkbuttons

Replies are listed 'Best First'.
Re^3: Perl/Tk : Trouble with commands and Checkbuttons
by Tanktalus (Canon) on Sep 16, 2005 at 14:52 UTC

    So a minor change to allow the closure to close on the current value would be to create new variables:

    #! /usr/bin/perl use warnings; use strict; use Tk; my $mw = MainWindow->new; $mw->title("Checkbutton Grid"); my $x_size = 5; my $y_size = 5; my %b_name; for (my $x=0; $x<$x_size; ++$x) { for (my $y=0; $y<$y_size; ++$y) { my $x_cord = $x; my $y_cord = $y; $mw -> Checkbutton ( -activebackground => "white", -command => sub { print "$x_cord,$y_cord\n +"; print "hi"; } ) -> grid ( -row => $x, -column => $y ); } } MainLoop;
    I'm not saying this is more efficient or better than your other example below (probably is neither), just that it's closer to the OP tried to do while still working.