Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Binding events to tk window close

Status
Not open for further replies.

nater

Programmer
Jun 14, 2002
21
CA
I'm trying to run an event (for example "Do you want to save settings before closing") to the 'X' button of a TK application. (Ideally I'd like to set this to run however the window is closed. IE ALT-F4, or a kill or end task, but if that's not possible, just adding a binding to the X button would be a big step.
Thanks..

Nathan
 
To detect when the user attempts to close a window, you need to use the wm protocol command to detect a "WM_DELETE_WINDOW" message from the window manager. Here's how you do it:

Code:
wm protocol . WM_DELETE_WINDOW {
    # Do whatever you like here
}

Of course, you can replace "." with the name of another toplevel window if your application has multiple toplevels.

As the comment above indicates, you can do anything you like in your WM_DELETE_WINDOW protocol handler, such as save your application's state in a data file, prompt the user if he or she really wants to quit, etc. In practice, if my application already has a "Quit" button or menu entry, usually I'll have my protocol handler simply invoke that button or menu entry. For example:

Code:
wm protocol . WM_DELETE_WINDOW {
    .mbar.file invoke "Quit"
}

The default WM_DELETE_WINDOW protocol handler simply destroys the toplevel (which exits your application, if it's your main window, "."). But if you override the default handler, then you don't have to destroy the window if you don't want to. In fact, the following code prevents a user from closing your window using any of the standard window manager techniques:

Code:
# In the following line, you must have at
# least one whitespace character between the
# { }. If you have no characters in the
# argument (an empty string), the wm protocol
# command interprets it as "restore the
# default protocol handler."

wm protocol . WM_DELETE_WINDOW { }
- Ken Jones, President
Avia Training and Consulting
866-TCL-HELP (866-825-4357) US Toll free
415-643-8692 Voice
415-643-8697 Fax
 
Man.. you're the most helpful guy ever. =) Thanks!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top