我撰寫了一個 Python (3.7) 應用程式,它使用 tkinter 作為 GUI,并在守護執行緒中運行 main 函式。當該守護程式執行緒中發生例外時,有沒有辦法破壞 tkinter 主回圈?
問題是該程式有多個模塊。如果其中任何一個發生這種情況,有沒有辦法殺死主回圈?否則,用戶將留下一個凍結的 GUI。
這是啟動執行緒的一段代碼:
import logging
import threading
from tkinter import *
from tkinter import ttk
def main_thread():
if check_input(): # user provided necessary input
program_thread = threading.Thread(target=program_pipeline) # runs main
program_thread.daemon = True # daemon thread can be killed anytime?
program_thread.start()
block_user_entries()
clear_results() # from a previous run
else:
logging.info("\n--------------- TRY AGAIN -------------------\n")
ublock_user_entries()
program_pipeline與多個模塊和包通信
當用戶單擊按鈕時執行緒開始
analyze_button = ttk.Button(frame, text="Analyze", state="normal", command=main_thread)
analyze_button.grid(column=2, row=0, pady=2, sticky=(W))
root.mainloop()
uj5u.com熱心網友回復:
如果我正確地解釋了這一點,那么您正在尋找一種從守護行程中中斷主執行緒的方法。
現在,通常這不是推薦的選項,您可以使用 low level 來做同樣的事情_thread.interrupt_main()。
如果您提供更多資訊,可以考慮更好的解決方案。
import _thread
import threading
import tkinter as tk
def program_pipeline():
try:
# DO STUFF
# calling other modules that may raise exception/error
raise ValueError("Error")
except BaseException as be:
print("Exception in daemon", be)
_thread.interrupt_main()
def main_thread():
program_thread = threading.Thread(target=program_pipeline)
program_thread.daemon = True
program_thread.start()
root = tk.Tk()
analyze_button = tk.Button(root, text="Analyze", state="normal", command=main_thread)
analyze_button.grid(column=2, row=0, pady=2, sticky=tk.W)
try:
root.mainloop()
except KeyboardInterrupt as kie:
print("exception in main", kie)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/422764.html
標籤:
上一篇:`std::osyncstream`如何管理輸出流?
下一篇:具有并發性的漏桶演算法
