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

Your code as posted doesn't compile. You've got a couple of typos in it...

Try this:

#! /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) { $mw -> Checkbutton ( -activebackground => "white", -command => sub { print "$x,$y\n"; print "hi"; } ) -> grid ( -row => $x, -column => $y ); } } MainLoop;

Note that when you want to call a subroutine in a -command line, you need to use the sub { ... } language. Note also that the values for $x and $y will be $x_size and $y_size respectively, because by the time you click on a check button, they've been incremented to those values - where they remain.

What you need to do is to associate a value (x, y) with each of the check buttons, and then use the value in your print statement.

Replies are listed 'Best First'.
Re^2: Perl/Tk : Trouble with commands and Checkbuttons
by pg (Canon) on Sep 16, 2005 at 06:05 UTC

    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.

      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.