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

13.1. Creating a Toplevel Widget

To create a toplevel, call Toplevel from the desired parent widget, usually the MainWindow widget (you already know that to create a main window, you must use MainWindow->new()). The returned item is a reference to the toplevel widget; the reference allows you to configure the widget, call methods on it, and place items within it. Here is a simple example:

use Tk;
$mw = MainWindow->new;
$mw->title("MainWindow");
$mw->Button(-text => "Toplevel", -command => \&do_toplevel)->pack();

MainLoop;
sub do_toplevel {
  if (! Exists($tl)) {
    $tl = $mw->Toplevel();
    $tl->title("Toplevel");
    $tl->Button(-text => "Close", 
                -command => sub { $tl->withdraw })->pack;
  } else {
    $tl->deiconify();
    $tl->raise();
  }
}

When you run this program, clicking on the Toplevel button in the main window creates the toplevel widget (if it needs to) and displays it. Clicking Close hides the toplevel from view. You need to test for the existence of the toplevel before you show it because you don't want to re-create it if it already exists and you don't want to try to show something that doesn't exist.

When the Close button is clicked, the toplevel is withdrawn. It still exists; it is just not visible to the user. This saves time the next time around by redisplaying the same window. You can also use withdrawif you don't want to show the toplevel while you are filling it with widgets. Simply use the withdrawmethod, place the interior widgets, and then redisplay the widget by using deiconify ...

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