首页 > 解决方案 > 在 tkinter 中关闭窗口之前执行某个命令

问题描述

我正在将 tkinter 与 python 一起使用。

按下关闭按钮时,是否可以在关闭窗口之前执行某个命令(例如 print ("hello"))?

我正在使用桌面环境的关闭按钮(以及最大化和最小化),而不是任何特殊的关闭按钮。

请注意,我问的是如何在关闭之前执行某个命令,而不是如何关闭窗口(这已经可以使用窗口按钮完成)。所以这不是这个问题的重复

标签: pythontkinter

解决方案


根据您在窗口关闭时要执行的操作,一种可能的解决方案是将您的 GUI 包装到一个类中,在with语句中对其进行初始化,然后在__exit__()方法中执行您的工作:

import tkinter


class MainWindow(object):

  def __init__(self):
    print("initiated ..")
    self.root = tkinter.Tk()

  def __enter__(self):
    print("entered ..")
    return self

  def __exit__(self, exc_type, exc_val, exc_tb):
    print("Main Window is closing, call any function you'd like here!")



with MainWindow() as w:
  w.root.mainloop()

print("end of script ..")

推荐阅读