Skip to content

Commit e802e70

Browse files
authored
fix: avoid crash when forcing app close during download (#59)
1 parent eb81e4a commit e802e70

File tree

1 file changed

+21
-4
lines changed

1 file changed

+21
-4
lines changed

src/tchMaterial-parser.pyw

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -699,11 +699,18 @@ class resource_helper: # 获取网站上资源的数据
699699

700700
def thread_it(func, args: tuple = ()) -> None: # 打包函数到线程
701701
t = threading.Thread(target=func, args=args)
702-
# t.daemon = True
702+
t.daemon = True
703703
t.start()
704704

705705
def ui_call(func, *args, **kwargs) -> None: # 在主线程执行 Tkinter UI 更新
706-
root.after(0, lambda: func(*args, **kwargs))
706+
if app_closing:
707+
return
708+
709+
try:
710+
root.after(0, lambda: (not app_closing) and func(*args, **kwargs))
711+
except Exception:
712+
# 主窗口销毁后,root.after 会抛错,直接忽略即可
713+
pass
707714

708715
def pick_ui_font_family() -> str: # 选择一个合适的字体
709716
try:
@@ -722,6 +729,7 @@ def pick_ui_font_family() -> str: # 选择一个合适的字体
722729

723730
session = requests.Session() # 初始化请求
724731
download_states = [] # 初始化下载状态
732+
app_closing = False
725733
access_token = None
726734
headers = { "X-ND-AUTH": 'MAC id="0",nonce="0",mac="0"' } # 设置请求头部,包含认证信息,其中 “MAC id” 即为 Access Token,“nonce” 和 “mac” 不可缺省但可为任意非空值
727735
session.proxies = {} # 全局忽略代理
@@ -778,10 +786,17 @@ def set_icon() -> None: # 设置窗口图标
778786
set_icon() # 设置窗口图标
779787

780788
def on_closing() -> None: # 处理窗口关闭事件
789+
global app_closing
790+
791+
if app_closing:
792+
return
793+
781794
if not all(state["finished"] for state in download_states): # 当正在下载时,询问用户
782795
if not messagebox.askokcancel("提示", "下载任务未完成,是否退出?"):
783796
return
784797

798+
app_closing = True
799+
785800
current_process = psutil.Process(os.getpid()) # 获取自身的进程 ID
786801
child_processes = current_process.children(recursive=True) # 获取自身的所有子进程
787802

@@ -791,8 +806,10 @@ def on_closing() -> None: # 处理窗口关闭事件
791806
except Exception: # 进程可能已经结束
792807
pass
793808

794-
# 结束自身进程
795-
sys.exit(0)
809+
try:
810+
root.destroy()
811+
except Exception:
812+
pass
796813

797814
root.protocol("WM_DELETE_WINDOW", on_closing) # 注册窗口关闭事件的处理函数
798815

0 commit comments

Comments
 (0)