start page | rating of books | rating of authors | reviews | copyrights

Book HomeMastering Perl/TkSearch this book

11.2. Creating a Toplevel Widget

To create a Toplevel, call Toplevel from the desired parent widget, usually the MainWindow widget (created with 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 MainWindow 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 recreate 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 withdraw if you don't want to show the Toplevel while you are filling it with widgets. Simply use the withdraw method, place the interior widgets, then use deiconify and raise to redisplay the widget.



Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.