python - Tkinter mainloop() 关闭窗口后不退出

标签 python tkinter

这不是 Python tkinter mainloop not quitting on closing the window 的副本

我有一个基于 tkinter 构建的应用程序。我观察到有时在我使用 X 按钮关闭窗口后,代码不会通过 mainloop() 行执行。这种情况完全随机发生,概率约为 10%。其余时间,它就像一个魅力。请问有没有什么办法可以强制。正如我所说,mainloop() 行上的代码块,因此在它之后调用 sys.exit() 没有帮助。

我正在使用 Python 3.9.8。

这不是 100% 可重现的,但这里有一些可能会触发问题:

from tkinter import *
root = Tk()
Label(root, 'hi').pack()
mainloop()
print('exited')

最佳答案

我的第一个想法是使用 root.mainloop() 而不是 tkinter.mainloop()。如果您使用多个窗口,这会有所不同。

也就是说,我很久以前在一些旧操作系统上看到过这个。从来没有弄清楚原因,所以我只是写了自己的退出函数,如下所示:

import tkinter as tk

def _quit():
    root.quit()
    root.destroy() 

root = tk.Tk()
root.protocol("WM_DELETE_WINDOW", _quit)
tk.Label(root, 'hi').pack()
root.mainloop()
print('exited')

关于python - Tkinter mainloop() 关闭窗口后不退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69960432/

相关文章:

python - 将列表划分为最少集合的最快方法,枚举所有可能的解决方案

python:在 easy_install 期间会发生什么?

python - 如何使用 PyPlot 摆脱鼠标悬停坐标?

python - tkinter unbind 似乎没有取消绑定(bind)

python - SQLite/Python 数据库检索和比较

python - 从 bokeh==2.1.1 升级到 bokeh==2.2.0 会破坏 figure.image_rgba()

python - 对单项字典列表进行排序?

python - 在 Tkinter TreeView 中插入数据以更正列时面临问题

python - 用Python播放音频的简单方法

python - 如何将 "game"(PyGame 或 Tk)录制到视频中?