Python Tkinter标签运行数小时后失效问题求助
Tkinter仪表盘运行数小时后标签重叠、停止更新的解决方法
问题根源
你的代码核心问题是每次调用updateLables时都会新建一批Label组件,旧的Label并没有被销毁或回收,只是被新Label覆盖。随着运行时间增加,内存中堆积的Label组件越来越多,最终导致Tkinter渲染异常(重叠、移位),同时事件循环被大量组件占用,出现视觉上的停止更新(但后台数据获取逻辑正常)。
解决方案
初始化时仅创建一次Label组件,后续更新只修改已有组件的文本和样式,不再重复创建;同时调整定时器逻辑,确保每次更新都获取最新数据。
修改后的完整代码
from datetime import datetime, timedelta from tkinter import * import tkinter as tk import math import requests import time import subprocess root = Tk() root.geometry("1920x1080") root.title("TITLE") root.configure(background="black", cursor='none') root.attributes('-fullscreen', True) # 初始化所有标签组件,仅创建一次 iz = Label(root, anchor='e', font=("Arial", 150, 'bold'), foreground="White", background="black") sz = Label(root, anchor='e', font=("Arial", 150, 'bold'), foreground="White", background="black") ssz = Label(root, anchor='e', font=("Arial", 150, 'bold'), foreground="White", background="black") dz = Label(root, anchor='e', font=("Arial", 150, 'bold'), foreground="White", background="black") # 固定标签位置,仅执行一次 iz.place(relx=0.85, rely=0.3, anchor='n', width='550', height='150') sz.place(relx=0.85, rely=0.1, anchor='n', width='550', height='150') ssz.place(relx=0.85, rely=0.5, anchor='n', width='550', height='150') dz.place(relx=0.85, rely=0.7, anchor='n', width='550', height='150') def createjson(): # 保留你原有的JSON获取逻辑,此处为示例返回 return [100, 200, 30, 400] def updateLables(): array = createjson() # 每次更新时获取最新数据 # 更新各标签的文本内容 iz.config(text=str(array[0])) sz.config(text=str(array[1])) ssz.config(text=str(array[3])) # 处理dz标签的文本和颜色逻辑 if isinstance(array[2], int): if array[2] > 0: d_text = f"+{array[2]}" dz.config(foreground="green") else: d_text = str(array[2]) dz.config(foreground="red") else: d_text = str(array[2]) dz.config(foreground="White") dz.config(text=d_text) # 定时触发下一次更新 root.after(5000, updateLables) # 启动更新循环 updateLables() tk.mainloop()
关键修改点
- 组件复用:将Label的创建和布局移到函数外部,仅执行一次,避免内存中堆积大量重复组件。
- 增量更新:使用
config方法修改已有Label的文本和样式,而非新建组件。 - 数据时效性:将
createjson()的调用移到updateLables内部,确保每次更新都获取最新数据,避免提前缓存导致的延迟。
内容的提问来源于stack exchange,提问作者Andrea
相关产品推荐
相关产品推荐

