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