我有一個類似于這篇文章的問題: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()
- 視窗顯示正確
- “向前邁進”之所以有效,是因為單擊按鈕時“做事”會列印到終端
- 通過按 X 或使用“退出”按鈕退出視窗都有效
問題: Python 應用程式永遠不會從終端退出,需要關閉終端。
我怎樣才能讓 Python 程式干凈利落地退出,這樣用戶就不需要關閉并重新打開一個新的終端視窗?
影片等相關參考資料:
- 使用 self.after 的影片:使用 tkinter移動圓圈
- 按鈕等待:讓 Tkinter 等待直到按下按鈕
- 原始的“退出”代碼:在 tkinter 類中退出程式
更新(解決方案):
(歸功于下面的兩個回復答案)
# 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)
這允許本機視窗的“X”關閉視窗和Tk 按鈕關閉視窗,同時仍然在終端中干凈地關閉 Python 應用程式。
uj5u.com熱心網友回復:
您的closing函式需要設定變數以使應用停止等待。
def closing(self):
self.destroy()
self.var.set("")
uj5u.com熱心網友回復:
在關閉函式中,需要呼叫exit退出程式。
def closing(self):
self.destroy() #closes tkinkter window
exit(0) #exits program
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/356581.html
