Mohit Mohit - 1 year ago 54
Perl Question

Destroy Widget in Tk not working

I have a Pertl Tk code, I want to close the main window and open another but after the first window is closing again when second window gets open te first window also appears.

The code

use strict;
use Tk;

my $mw;

#Calling the welcome_window sub
welcome_window();

sub welcome_window{

#GUI Building Area
$mw = new MainWindow;

my $frame_header = $mw->Frame();
my $header = $frame_header -> Label(-text=>"Molex Automation Tool");
$frame_header -> grid(-row=>1,-column=>1);
$header -> grid(-row=>1,-column=>1);

my $region_selected = qw/AME APN APS/;

my $frame_sub_header = $mw->Frame();
my $sub_header = $frame_sub_header -> Label(-text=>"Region Selection");
$frame_sub_header -> grid(-row=>2,-column=>1);
$sub_header -> grid(-row=>2,-column=>1);


my $frame_region = $mw->Frame();
my $label_region = $frame_region -> Label(-text=>"Region:");
my $region_options = $frame_region->Optionmenu(
-textvariable => \$region_selected,
-options => [@regions],
);
$frame_region -> grid(-row=>3,-column=>1);
$label_region -> grid(-row=>3,-column=>1);
$region_options -> grid(-row=>3,-column=>2);

my $frame_submit = $mw->Frame();
my $submit_button = $frame_submit->Button(-text => 'Go!',
-command => \&outside,
);
$frame_submit -> grid(-row=>4,-column=>1,-columnspan=>2);
$submit_button -> grid(-row=>4,-column=>1,-columnspan=>2);

MainLoop;
}

#This sub is just made to close the main window created in Welcome_Wiondow() sub and call the second_window()

sub outside{

$mw -> destroy;
sleep(5);
second_window();
}


sub second_window{

my $mw2 = new MainWindow;
my $frame_header2 = $mw2->Frame();
my $header2 = $frame_header2 -> Label(-text=>"Molex Automation Tool");
$frame_header2 -> grid(-row=>1,-column=>1);
$header2 -> grid(-row=>1,-column=>1);

my $frame_sub_header2 = $mw2->Frame();
my $sub_header2 = $frame_sub_header2 -> Label(-text=>"Tasks Region Wise");
$frame_sub_header2 -> grid(-row=>2,-column=>1);
$sub_header2 -> grid(-row=>2,-column=>1);

MainLoop;
}


I have reduced the code and only put the relevant lines. Now please let me know why I can't kill the main window opened in sub welcome_window() in the sub outside(). Currently what it does is it closes the main windows during the sleep command but as soon as I open the main windows of the second_windows, the windows of welcome_window also reappears.


Got the above code working now, there was some issue in the logic
which was calling the welcome_window again. Thank you all for your
help.

Answer Source

You can't have more than one MainWindow. Create a Toplevel window for the initial one, use withdraw to hide the real main window at the start, make it reappear with deiconify:

my $mw = MainWindow->new;
my $tl = $mw->Toplevel;
$tl->protocol(WM_DELETE_WINDOW => sub {
    $mw->deiconify;
    $tl->DESTROY;
});
$mw->withdraw;
MainLoop();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download