5

I'm using Tcl/Tk to build a GUI, for Linux environment and I saw that it's possible to "catch" a press on the 'x' button of the window (The button on the top right corner that closes the program).

How can I catch those events?

SIMEL
  • 8,745
  • 28
  • 84
  • 130

2 Answers2

8

To take control of requests to delete a window, configure a suitable protocol handler:

wm protocol . WM_DELETE_WINDOW {
    if {[tk_messageBox -message "Quit?" -type yesno] eq "yes"} {
       exit
    }
}

The default behavior (i.e., if the protocol handler is the empty string) is to just destroy the toplevel to which the request was made.

Donal Fellows
  • 133,037
  • 18
  • 149
  • 215
5

Bind to the WM_DELETE_WINDOW "protocol message" using the wm protocol command.

Also note that if you just want track window destruction (on a higher level), just bind to its <Destroy> event.

kostix
  • 51,517
  • 14
  • 93
  • 176
  • 3
    Binding to `` on toplevels can be tricky, since you also get it for the sub-widgets of the toplevel (due to general event handling rules). – Donal Fellows Nov 02 '11 at 14:52
  • @Donal Fellows, agreed. One trick is to embed our own window name in the callback and then skip those bogus calls, like in `bind $w [list cb $w %W]; proc cb {w1 w2} { if {$w1 ne $w2} return; # otherwise do whatever is needed }` – kostix Nov 02 '11 at 16:07
  • 2
    I've done that in the past. The other way is to see whether the event window is the same as the toplevel of the event window: `if {"%W" eq [winfo toplevel %W]} ...` (or equivalent in a procedure). – Donal Fellows Nov 02 '11 at 16:14