代码
import tkinter as tk
from tkinter import *
import threading
def main():
root = tk.Tk()
# Gets the requested values of the height and width.
window_width = root.winfo_reqwidth()
window_height = root.winfo_reqheight()
# Gets both half the screen width/height and window width/height
position_right = int(root.winfo_screenwidth()/2 - window_width/2)
position_down = int(root.winfo_screenheight()/2 - window_height/2)
# Positions the window in the center of the page.
root.geometry(f"+{position_right}+{position_down}")
app = MainWindow(root)
root.mainloop()
class MainWindow:
def __init__(self,master):
self.master = master
self.master.title("Sign off check")
self.master.geometry('800x350')
self.frame = Frame(self.master)
self.frame.pack(fill="both", expand=True)
def refresh_progress():
threading.Timer(5.0, refresh_progress).start()
refresh_progress()
if __name__ == '__main__':
main()
输出
通过 CMD 运行 - 打开简单的空白 Tkinter 窗口,并且函数 (deffresh_progress():
) 每 5 秒运行一次。
问题
我的问题是 - 当我关闭 Tkinter 窗口时(按右上角的“x”)。 CMD 窗口仍在后台运行。
问题
如何在 Tkinter 窗口关闭后立即停止 CMD 在后台运行?
最佳答案
在这里使用我的完整代码
import sys
import tkinter as tk
from tkinter import *
import threading
def on_closing():
# you can add a various command here, for example like messagebox or something
timer.cancel()
root.destroy()
sys.exit()
def main():
global root
root = tk.Tk()
root.protocol("WM_DELETE_WINDOW", on_closing) # when user click "X"
# Gets the requested values of the height and width.
window_width = root.winfo_reqwidth()
window_height = root.winfo_reqheight()
# Gets both half the screen width/height and window width/height
position_right = int(root.winfo_screenwidth()/2 - window_width/2)
position_down = int(root.winfo_screenheight()/2 - window_height/2)
# Positions the window in the center of the page.
root.geometry(f"+{position_right}+{position_down}")
app = MainWindow(root)
root.mainloop()
class MainWindow:
def __init__(self,master):
self.master = master
self.master.title("Sign off check")
self.master.geometry('800x350')
self.frame = Frame(self.master)
self.frame.pack(fill="both", expand=True)
def refresh_progress():
global timer
timer = threading.Timer(5.0, refresh_progress)
timer.start()
refresh_progress()
if __name__ == '__main__':
main()
通过将协议(protocol)“WM_DELETE_WINDOW”添加到root
来解决
关于python - 使用Threading时如何关闭后台运行的CMD?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59209552/