Quitting a Tkinter application with confirmation

Peter Kleiweg p.c.j.kleiweg at rug.nl
Wed Nov 16 13:37:09 EST 2005


I have an application written in Tkinter. There is a menu item 
'quit' that calls the function 'quit'. If 'quit' is called, it 
first checks if there is unsaved data. If there is, it won't let 
the application exit unless you confirm to disregard the 
changes.

So far, so good.

I want the program to behave identical if the 'close' button of 
the application window is clicked. I tried the code below, 
using a class derived from Tk that redefines the destroy 
method. That seems to work. At least on Linux. 

My questions: 

Is this the correct and save way to do this? Will it work on any 
operating system? Shouldn't I do some event capturing instead? 
(Capture the SIGTERM or SIGQUIT, sent by the Window manager to 
the application.)

from Tkinter import *
import tkMessageBox

def quit():
    if not changes:
        root.quit()
    else:
        if tkMessageBox.askyesno(_('Quit'), _('Project is not saved. Ignore changes and quit?')):
            root.quit()

class myTk(Tk):
    def destroy(self):
        quit()

root = myTk()

-- 
Peter Kleiweg  L:NL,af,da,de,en,ia,nds,no,sv,(fr,it)  S:NL,de,en,(da,ia)
info: http://www.let.rug.nl/~kleiweg/ls.html



More information about the Python-list mailing list