python - 有没有办法在窗口破坏 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()
解决方案
你可以看看这个关于如何处理退出窗口的答案。
简而言之,您可以这样做:
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()
推荐阅读
- java - 如何使用复杂节点实时过滤 Firebase 数据库中的数据
- python - 如何在 Synology 上安装 Pip 3 和 Python Lib MySQLdb
- ruby - 如何使用 Rubymine 并行运行黄瓜测试
- typescript - TSLint:有序导入配置
- reactjs - 我对 reactJS 的跨域有一些问题“错误:引发了跨域错误。”
- javascript - 根据方位计算 x 和 y
- c++ - 无法将多维数组传递给函数
- angular - 来自服务器的响应为空
- python - how to keep Several parts of the matrix and zero the rest?
- sql - Postgres 中的慢查询优化