Which method can I override for cleanup task when a Tkinter.Tk window in Python?

耗尽温柔 提交于 2019-12-11 06:06:49

问题


class MainGUI(Tkinter.Tk):
    # some overrides

# MAIN 

gui = MainGUI(None)
gui.mainloop()

But I need to do some cleanup when the window is closed by the user. Which method in Tkinter.Tk can I override?


回答1:


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.




回答2:


You can set up a binding that gets fired when the window is destroyed. Either bind to <Destroy> or add a protocol handler for WM_DELETE_WINDOW.

For example:

def callback():
    # your cleanup code here

...
root.protocol("WM_DELETE_WINDOW", callback)


来源:https://stackoverflow.com/questions/2954396/which-method-can-i-override-for-cleanup-task-when-a-tkinter-tk-window-in-python

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