干净地退出 Python Tkinter 应用程序,同时还在 "after" 循环中的按钮上使用 "wait_variable" 函数

Exit Python Tkinter app cleanly while also using "wait_variable" function on a button in an "after" loop

我有类似的问题post:Exit program within a tkinter class

我对这个问题的变体涉及 wait_variable 在按钮上使用以控制应用程序中的“前进”,但也允许应用程序干净地关闭 .

查看下面我的代码:

# To see output unbuffered:
#   python -u delete_win_test.py

import tkinter as tk
from tkinter import *


class GUI(Tk):
    def __init__(self):
        super().__init__()

        # Close the app when the window's X is pressed
        self.protocol("WM_DELETE_WINDOW", self.closing)

        # When this var is set to 1, the move function can continue
        self.var = tk.IntVar()

        # Close the app if the button is pressed
        button = tk.Button(self, text="Exit",
                           command=self.destroy)
        button.place(relx=.5, rely=.5, anchor="c")

        # Step forward
        self.step_button = tk.Button(self, text="Step",
                                     command=lambda: self.var.set(1))
        self.step_button.place(relx=.5, rely=.75, anchor="c")

    def move(self):
        print("doing stuff")  # simulates stuff being done
        self.step_button.wait_variable(self.var)
        self.after(0, self.move)

    def closing(self):
        self.destroy()


app = GUI()
app.move()
app.mainloop()

问题: Python 应用程序永远不会从终端退出,需要关闭终端。

如何让 Python 程序干净地退出,这样用户就不需要关闭并重新打开新终端 window?

动画等相关参考:

更新(解决方案):

(归功于以下两个回复答案)

         # Close the app if the button is pressed
         button = tk.Button(self, text="Exit",
-                           command=self.destroy)
+                           command=self.closing)
         button.place(relx=.5, rely=.5, anchor="c")
 
         # Step forward
...
     def closing(self):
         self.destroy()
+        self.var.set("")
+        exit(0)

这允许本机 window 的“X”关闭 window Tk 按钮关闭 window 同时仍然在终端中干净地关闭 Python 应用程序

您的 closing 函数需要设置变量以使应用停止等待。

def closing(self):
    self.destroy()
    self.var.set("")

在关闭函数中,需要调用exit退出程序

def closing(self):
    self.destroy() #closes tkinkter window
    exit(0) #exits program