首页 > 解决方案 > 有没有办法在窗口破坏 tkinter 时执行 smth

问题描述

当在 tkinter 中手动关闭窗口并且不知道这样做的方法/功能时,我正在尝试做某事。我试图以较小的规模做的一个简单的例子。

from tkinter import *

root = Tk()
rootIsClosed = False # how to do this? How to make it True?
if rootIsClosed:     # ?
    new_win = Tk()
    x = Label(new_win, text='why did you close the program').pack()

标签: pythontkinter

解决方案


你可以看看这个关于如何处理退出窗口的答案。

简而言之,您可以这样做:

from tkinter import *
root = Tk() #create new root

def on_close():
    #this is the code you provided

    new_win = Tk()
    x = Label(new_win, text='why did you close the program').pack()

root.protocol("WM_DELETE_WINDOW", on_close) # main part of the code, calls on_close
root.mainloop()

请注意,这不允许您实际关闭窗口,因此您可以这样做来关闭窗口:

from tkinter import *
root = Tk()

def on_close():
    new_win = Tk()
    x = Label(new_win, text='why did you close the program').pack()
    root.destroy() #only difference, root.destroy closes the original window.

root.protocol("WM_DELETE_WINDOW", on_close)
root.mainloop()

推荐阅读