Skip to Main Content
Learning Perl/Tk
book

Learning Perl/Tk

by Nancy Walsh
January 1999
Beginner content levelBeginner
373 pages
9h 43m
English
O'Reilly Media, Inc.
Content preview from Learning Perl/Tk

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. ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Mastering Perl/Tk

Mastering Perl/Tk

Stephen Lidie, Nancy Walsh

Publisher Resources

ISBN: 1565923146Supplemental ContentCatalog PageErrata