Intercept Tkinter “Exit” command?

社会主义新天地 提交于 2019-11-27 23:13:25
Bryan Oakley

You want to use the wm_protocol method of the toplevel window. Specifically, you are interested in the WM_DELETE_WINDOW protocol. If you use that method, it allows you to register a callback which is called when the window is being destroyed.

Usage:

root.protocol("WM_DELETE_WINDOW", app.on_delete)

You can use python atexit module.

For example:

import atexit

def doSomethingOnExit():
    pass

atexit.register(doSomethingOnExit)
O.C.

FWIW: It is also possible to assign a widget-specific behavior.

If you want an action to occur when a specific widget is destroyed, you may consider overriding the destroy() method. See the following example:

class MyButton(Tkinter.Button):
    def destroy(self):
        print "Yo!"
        Tkinter.Button.destroy(self)

root = Tkinter.Tk()

f = Tkinter.Frame(root)
b1 = MyButton(f, text="Do nothing")
b1.pack()
f.pack()

b2 = Tkinter.Button(root, text="f.destroy", command=f.destroy)          
b2.pack()

root.mainloop()

When the button 'b2' is pressed, the frame 'f' is destroyed, with the child 'b1' and "Yo!" is printed.

I posted the same answer on this topic.

piertoni

In my case, the following code didn't work:

root.protocol("WM_DELETE_WINDOW", app.on_delete)  # doesn't work

However, it worked using this form:

root.wm_protocol ("WM_DELETE_WINDOW", app.on_delete)  # does work
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!