在关闭tkinter中的窗口之前执行某个命令

时间:2018-06-15 11:52:14

标签: python tkinter

我正在使用tkinter和python。

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

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

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

的重复

2 个答案:

答案 0 :(得分:1)

根据窗口关闭时您想要做什么,一个可能的解决方案是将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 ..")

答案 1 :(得分:-1)

这是我想出的:

import tkinter as tki

def good_bye(*args):
    print('Yo, dawg!')

root_win = tki.Tk()
my_button = tki.Button(root_win, text='I do nothing')
my_button.pack(padx=20, pady=20)
my_button.bind('<Destroy>', good_bye)
root_win.mainloop()

当窗口小部件被销毁时触发事件,这在关闭主窗口时发生。奇怪的是,如果将事件绑定到主窗口,则会触发两次。也许更有知识的人可以对此有所了解。

相关问题