You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Tkinter窗口无原因卡顿崩溃,无线程加载屏运行后未响应如何解决?

问题原因
  • 代码直接阻塞了Tk的主事件循环:Tk所有界面交互、重绘、系统消息响应都依赖mainloop()处理消息队列,但你的__init__方法里先执行了PBar_animation(),这个函数里的for循环+time.sleep(0.1)是完全阻塞的同步逻辑,跑完2000次需要200秒,这期间mainloop()根本没有启动,仅靠update_idletasks()只能处理界面重绘类的闲置任务,无法响应鼠标移动、窗口点击、系统保活检测这类系统消息,操作系统检测到窗口长时间不响应消息队列就会标记为「未响应」,严重时就会强制结束进程。
  • indeterminate模式的进度条本身就自带动画效果,不需要手动循环修改value,你写的手动累加逻辑完全是多余的。
无线程的修复方案

用Tk自带的after()方法实现非阻塞的定时调度,完全替代阻塞的for循环+sleep逻辑,不需要引入额外线程,符合你的开发要求:

from tkinter import Tk, Label, ttk

class Loading_Screen:
    def __init__(self):
        self.root = Tk()
        self.root.title('Waiting for Connection...')
        self.root.config(bg = '#1F2700')
        self.root.geometry('800x400')

        theme = ttk.Style()
        theme.theme_use('winnative')
        theme.configure('orange.Horizontal.TProgressbar', background ='orange')

        loading_txt = Label(self.root, text = 'Waiting for Connection...', font = 'Teko 15', bg = '#1F2700')
        loading_txt.place(x=200, y =145)

        self.PBar = ttk.Progressbar(self.root,
                                    orient = 'horizontal', mode = 'indeterminate', length = 300, style='orange.Horizontal.TProgressbar')
        self.PBar.place(x=200, y=180)
        # 启动进度条自带动画
        self.PBar.start()
        # 200秒后自动关闭窗口,对应你原来2000*0.1s的逻辑
        self.root.after(200*1000, self.close_window)
        # 直接启动主事件循环
        self.root.mainloop()

    def close_window(self):
        self.PBar.stop()
        self.root.destroy()
        exit(0)

if __name__ == "__main__":
    Loading_Screen()

修改后全程不会阻塞主事件循环,所有系统消息、界面交互都能正常响应,不会出现未响应问题。

内容的提问来源于stack exchange,提问作者GreenManchego1984

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 05:36:03