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

Jay Jarvinen jayjarvinen at gmail.com
Tue Mar 15 03:40:24 PST 2005


Jay O'Neill, I'm kinda late, hopefully you've figured out your
Tk::bind issue. I didn't have the original message to reply to, but
for the archive ...

In this case, since the bind event is short, I'd just do:
$c->bind($i, "<Enter>", sub { $c->itemconfigure($i, -fill => 'red'); });

But here's how you had it, with a small twist:

-Jay J.

#!/usr/bin/perl -w

use strict;
use Tk;

my $mw = MainWindow->new(-title => "Press 'q' to exit");
$mw->bind("<KeyPress-q>", sub { warn "Exiting!\n"; exit(0); });

my $c = $mw->Scrolled('Canvas')->pack();

foreach my $i (1 .. 5) {
	$c->create('text', 50, $i * 20,
				  -text => "Hover Me! $i",
				  -tags => $i);

	$c->bind($i, "<Enter>", [\&stuff, $i, 'red']);
	$c->bind($i, "<Leave>", [\&stuff, $i, $c->itemcget($i, -fill)]);
	##-- set it back to original fill color on Leave event
}

Tk::MainLoop();

sub stuff {
	my ($this_c, $this_i, $color) = @_;
	##-- named 'this' to demonstrate Tk is passing canvas ref and our data

	$this_c->itemconfigure($this_i, -fill => $color);
#	my $ev = $Tk::event; warn "Event Type: ", $ev->T, "\n"; ##-- OR:
#	warn "Event Type: ", $Tk::event->T, "\n";
}


More information about the Mpls-pm mailing list