vikee has asked for the wisdom of the Perl Monks concerning the following question:

Hello, 
how can I catch in Perl/Tk the closing of the program? 
something like OnExit in C. I tried $top->bind
('<Destroy>' ...) but it is called everytime when a widget is destroyed. 
I need only when the program is closed.

Replies are listed 'Best First'.
Re: Tk onExit
by pg (Canon) on Jul 21, 2004 at 09:05 UTC

    Not destroy, but something like this: (code is tested with 5.8.4 on windows 2000)

    use Tk; use strict; use warnings; my $mw = new MainWindow(); $mw->protocol("WM_DELETE_WINDOW", sub {print "abc\n"; exit;}); MainLoop;
    A reply falls below the community's threshold of quality. You may see it by logging in.
Re: Tk onExit
by arden (Curate) on Jul 21, 2004 at 20:15 UTC
    Here's how I do it with my applications. Create a subroutine exitApp and use OnDestroy with the first MainWindow to call it when somebody destroys (closes) that main widget. That is the definition of the program closing.
    my $mw = new MainWindow(); $mw->OnDestroy( \&exitApp );
    - - arden.
Re: Tk onExit
by graff (Chancellor) on Jul 22, 2004 at 01:11 UTC
    Have you tried using an END{...} block in the program? Just curious -- it's the first thing I would try, because it's the standard method for hooking into perl's shut-down procedure, but I've never tried it in a Tk app, and I don't know whether that raises issues.

    If you did try it, it would be worthwhile to post your findings about that.

      An END { } block will be executed after the Tk window is destroyed, so this won't help the original questioner.