erk*_*gur 26 python tkinter button
当用户按下我创建的关闭时 Button
,某些任务在退出之前执行.但是,如果用户单击[X]
窗口右上角的按钮关闭窗口,则无法执行这些任务.
如何覆盖用户单击[X]
按钮时发生的情况?
Nic*_*sta 43
听起来好像你的保存窗口应该是模态的.
如果这是一个基本的保存窗口,为什么要重新发明轮子?
Tk
有一个tkFileDialog
为此目的.
如果你想要的是覆盖破坏窗口的默认行为,你可以简单地做:
root.protocol('WM_DELETE_WINDOW', doSomething) # root is your root window
def doSomething():
# check if saving
# if not:
root.destroy()
Run Code Online (Sandbox Code Playgroud)
这样,destroy()
当有人关闭窗口时(无论如何),您可以拦截呼叫并执行您喜欢的操作.
使用该方法procotol
,我们可以WM_DELETE_WINDOW
通过将协议与函数的调用相关联来重新定义协议,在这种情况下,函数被调用on_exit
:
import tkinter as tk
from tkinter import messagebox
class App(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.title("Handling WM_DELETE_WINDOW protocol")
self.geometry("500x300+500+200")
self.make_topmost()
self.protocol("WM_DELETE_WINDOW", self.on_exit)
def on_exit(self):
"""When you click to exit, this function is called"""
if messagebox.askyesno("Exit", "Do you want to quit the application?"):
self.destroy()
def center(self):
"""Centers this Tk window"""
self.eval('tk::PlaceWindow %s center' % app.winfo_pathname(app.winfo_id()))
def make_topmost(self):
"""Makes this window the topmost window"""
self.lift()
self.attributes("-topmost", 1)
self.attributes("-topmost", 0)
if __name__ == '__main__':
App().mainloop()
Run Code Online (Sandbox Code Playgroud)