14.2. Arguments Sent to the Callback
The first argument to a callback assigned with bind is always a reference to the calling widget. This is true even when you bind to a widget class. You can use the reference passed in to retrieve information about the widget from which the sequence was invoked.
Here's an example of using a single entry widget:
$entry = $mw->Entry()->pack;
$entry->bind("<Return>", \&hit_return);
sub hit_return {
my ($e) = @_;
print "Entry contained: ", $e->get, "\n";
}
When you use bind to invoke a callback on an entire widget class, it makes the job of determining which widget was the subject of the event much easier:
$mw->Scrolled("Text")->pack(-expand => 1, -fill => 'both');
$mw->Scrolled("Text")->pack(-expand => 1, -fill => 'both');
$menu = $mw->Menu(-menuitems => [ ["command" => "Save",
-command => \&save_file],
["command" => "Open",
-command => \&open_file]
],
-tearoff => 0);
$mw->bind(Tk::Text, "<Button-3>",
sub { $menu->Popup(-popover => 'cursor') });
sub save_file {
my ($text) = @_;
open(FH, ">outfile") || die "Couldn't open outfile for writing";
print FH $text->get("1.0", "end");
close (FH);
}
The call to bind uses Tk::Text as the first argument. This will cause the bind to be applied to every text widget in the application. In this example, no matter which text widget is clicked, its contents will be written to "outfile". The application might also prompt the user for a different filename at that point, allowing it to actually do something useful. ...