aoma 发表于 2012-08-29 12:43

求助:如何让perl/Tk主窗口关闭(点击主窗口右上方的关闭按钮)时执行特定的子例程

各位大侠帮忙一下: 如何让perl/Tk主窗口关闭时执行特定的子例程

目的:在主窗口中有一个Text控件,在关闭主窗口(即mouse点击主窗口右上方的关闭按钮的时候)可以执行一个子例程,用来保存Text控件的内容
如果用一个Button来关联是可以的,就是不知道如何在点击主窗口右上方的关闭按钮的时候实现同样的功能


button关联的实现是这样的:
my $button20 = $frame->Button(-text=>decode('utf-8',"退出"),-fg=>"red",-font => "fixed 12 bold",-command =>\&leave);
sub leave {
      my $str = $txt->Contents();
      my $file = time;
      system("echo -e \" $str\" >/var/log/mylog${file}");
      exit;
      }

kk861123 发表于 2012-08-29 16:24

回复 1# aoma


    很久没写Tk了,手头没有环境,试试:$frame->protocol('WM_DELETE_WINDOW' => \&leave);

aoma 发表于 2012-08-29 19:32

是的,你的语句真的行,谢谢kk861123兄

我在后面加了一行就可以了
因为frame是建立在主窗口上的,因此我下面的语句是可行,已验证了
$mw->protocol('WM_DELETE_WINDOW' => \&leave);

下面找到的Master perl/Tk中有关protocol的参考

The protocol method controls the following window properties: WM_DELETE_WINDOW, WM_SAVE_YOURSELF, and WM_TAKE_FOCUS. The callback (if any) associated with each property will be invoked when the window manager recognizes the event associated with the property:

$toplevel->protocol ( [ property_name] [, callback ] );
The WM_DELETE_WINDOW property callback is invoked when the window has been deleted by the window manager. By default, there is a callback assigned by Perl/Tk that destroys the window. If you assign a new callback, your callback will be invoked instead of the default callback. If you need to save data associated with that window, do so in the callback, then invoke $toplevel->destroy() to mimic the correct behavior afterward.

The other two properties, WM_SAVE_YOURSELF and WM_TAKE_FOCUS, are used much less commonly. For instance, WM_TAKE_FOCUS is used in Unix systems but not in Win32. The presence of these properties is dependent on the window system you are running. If your application will be running on multiple systems, don't expect these properties to always be available. To find out if they are available, assign each one a callback that does a print, then run the application to see if the print is ever invoked.

If you leave out the callback when you use protocol, the current callback assigned to that property will be returned (or an empty string, if there isn't a current callback assigned). You can remove the callback by sending an empty string instead of the callback. If neither argument is specified, the method returns a list of all properties that have callbacks assigned to them.


页: [1]
查看完整版本: 求助:如何让perl/Tk主窗口关闭(点击主窗口右上方的关闭按钮)时执行特定的子例程