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

Raspberry Pi中Tkinter窗口在while True循环前调用无法显示的问题

问题原因

你的代码里while True是死循环,会一直霸占主线程,导致后面的sc.mainloop()完全没机会运行。Tkinter的窗口渲染、事件响应全靠mainloop()驱动,所以窗口根本弹不出来。

解决方案

用Tkinter自带的after()方法替换死循环,定时检查线程状态,这样不会阻塞主循环。同时优化线程管理逻辑:

import FillingMachineClass
import datetime
import threading
import tkinter

sc = tkinter.Tk()

fm = FillingMachineClass.FillingMachine(1)

# 初始化并启动三个工作线程,设为守护线程随主线程退出
t1 = threading.Thread(target=fm.detect_zero_sensor, daemon=True)
t1.start()
t2 = threading.Thread(target=fm.carousel_opertion, daemon=True)
t2.start()
t3 = threading.Thread(target=fm.line_jamming, daemon=True)
t3.start()

def check_and_restart_threads():
    global t1, t2, t3
    # 检查t1是否存活,已结束则重启
    if not t1.is_alive():
        t1 = threading.Thread(target=fm.detect_zero_sensor, daemon=True)
        t1.start()
    # 检查t2
    if not t2.is_alive():
        t2 = threading.Thread(target=fm.carousel_opertion, daemon=True)
        t2.start()
    # 检查t3
    if not t3.is_alive():
        t3 = threading.Thread(target=fm.line_jamming, daemon=True)
        t3.start()
    # 每隔100毫秒重复检查一次,可根据需求调整间隔
    sc.after(100, check_and_restart_threads)

# 启动定时检查任务
check_and_restart_threads()

# 启动Tkinter主事件循环
sc.mainloop()
补充说明
  • daemon=True:设置线程为守护线程,当主窗口关闭(主线程退出)时,这些工作线程会自动终止,避免程序残留后台进程。
  • after()方法:Tkinter的非阻塞定时调用方式,不会像死循环那样卡住主线程,保证窗口能正常渲染和响应操作。
  • 如果你的线程函数内部本身包含循环逻辑(比如一直在检测传感器),那其实不需要重启线程,只要启动一次就能持续运行,此时可以去掉检查重启的逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 21:20:12