[Mpls-pm] Issue with binding events to Tk canvas objects.

Ian Malpass ian at indecorous.com
Thu Sep 23 14:09:39 CDT 2004


On Wed, 22 Sep 2004, Jay O'NEIL wrote:

> # this works as expected
> $canvas->bind(2,"<Enter>",sub{&stuff(2);});
> $canvas->bind(3,"<Enter>",sub{&stuff(3);});
> $canvas->bind(4,"<Enter>",sub{&stuff(4);});
>
> # this does not work as expected
> $foo = 2;
> $canvas->bind($foo,"<Enter>",sub{&stuff($foo);});
> $foo = 3;
> $canvas->bind($foo,"<Enter>",sub{&stuff($foo);});
> $foo = 4;
> $canvas->bind($foo,"<Enter>",sub{&stuff($foo);});
> # this is the only object that gets acted upon

Isn't it some sort of closure-related problem? You end up with a reference 
to $foo in &stuff, and its final value is 4, so all your callbacks call 
&stuff(4). Or something.

Maybe something like:

     for my $foo ( 2..4 ) {
         $canvas->bind($foo,"<Enter>",&stuff($foo););
     }

     sub stuff {
         my $index = shift;
         return sub { $canvas->itemconfigure($index,-fill=>'red'); };
     }

<disclaimer>I know nothing about Tk (and, for that matter, precious little 
about closures) and I haven't actually *tested* the above.</disclaimer>

Ian

-
---------------------------------------------------------------------------

The soul would have no rainbows if the eyes held no tears.

Ian Malpass
<ian at indecorous.com>


More information about the Mpls-pm mailing list