【问题标题】:Overriding Tkinter "X" button control (the button that close the window) [duplicate]覆盖Tkinter“X”按钮控件(关闭窗口的按钮)[重复]
【发布时间】:2011-03-18 17:44:45
【问题描述】:

当用户按下我创建的 close Button 时,会在退出前执行一些任务。但是,如果用户单击窗口右上角的[X] 按钮关闭窗口,我将无法执行这些任务。

如何覆盖用户单击[X] 按钮时发生的情况?

【问题讨论】:

    标签: python button tkinter


    【解决方案1】:

    我在 Tkinter here 上找到了一个参考。它并不完美,但几乎涵盖了我所需要的一切。我认为第 30.3 节(事件类型)有帮助,它告诉我们小部件有一个“销毁”事件。我想 .bind() 将您的保存作业添加到主窗口的该事件应该可以解决问题。

    您也可以调用 mainwindow.overrideredirect(True)(第 24 节),它会通过标题栏中的按钮禁用最小化、调整大小和关闭。

    【讨论】:

    • overrideredirect(flag=None) [#] 设置或获取覆盖重定向标志。如果非零,这会阻止窗口管理器装饰窗口。也就是说,窗口不会有标题和边框,也无法通过普通方式移动或关闭。
    【解决方案2】:

    听起来你的保存窗口应该是modal

    如果这是一个基本的保存窗口,你为什么要重新发明轮子? Tk 有一个 tkFileDialog 用于此目的。


    如果你想要覆盖销毁窗口的默认行为,你可以简单地这样做:

    root.protocol('WM_DELETE_WINDOW', doSomething)  # root is your root window
    
    def doSomething():
        # check if saving
        # if not:
        root.destroy()
    

    这样,当有人(以任何方式)关闭窗口时,您可以拦截destroy() 调用并做您喜欢的事情。

    【讨论】:

      【解决方案3】:

      您要查找的命令是wm_protocol,将其指定为"WM_DELETE_WINDOW" 作为要绑定的协议。它允许您定义一个在窗口管理器关闭窗口时调用的过程(当您单击[x] 时会发生这种情况)。

      【讨论】:

        【解决方案4】:

        使用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()
        
        猜你喜欢
        • 2010-12-12
        • 2020-11-13
        • 1970-01-01
        • 1970-01-01
        • 2019-01-17
        • 2012-12-17
        • 2011-11-06
        • 2013-06-11
        • 2021-09-25
        相关资源
        最近更新 更多