import tkinter as tk
import randomimport seriallis=[]
for i in range(50):lis.append(i+1)
# 打开串行端口
ser = serial.Serial('COM3', 9600) # 9600为波特率,根据实际情况进行调整# 初始化数据
lis = [random.randint(15, 35) for _ in range(50)]def update_data():global lis# 模拟数据更新# lis = [random.randint(15, 35) for _ in range(50)]try: if ser.in_waiting > 0: # 如果串口有数据可读 data = ser.read() # 读取一行数据并解码为字符串ser.reset_input_buffer()tmp=(ord(data)+100)/10print("\r测到的温度是:", tmp,'°C',end=' ')lis.append(tmp)while len(lis)>50:lis.pop(0)print(lis,end=' ')except Exception as error:print(error)ser.close() # 捕获Ctrl+C中断信号后关闭串口 print("程序已停止")passdef draw_chart(canvas, data):canvas.delete("all") # 清除画布上的所有内容# 以下是绘图代码,与之前相同,只是增加了canvas参数margin = 40width = 600 - 2 * marginheight = 400 - 2 * marginx_scale = width / (len(data) - 1)y_scale = height / (35 - 10)canvas.create_line(margin, 400 - margin, 600 - margin, 400 - margin) # X轴canvas.create_line(margin, 400 - margin, margin, margin) # Y轴for i in range(len(data)):x = margin + i * x_scaleif i % 5 == 0: # 每5个数据点标记一次canvas.create_text(x, 400 - margin + 20, text=str(i))for value in range(int(10), int(35) + 1, 5):y = 400 - margin - (value -10) * y_scalecanvas.create_line(margin - 5, y, margin, y)canvas.create_text(margin - 20, y, text=str(value))points=[]for i in range(len(data)):x = margin + i * x_scaley = 400 - margin - (data[i] - 10) * y_scalecanvas.create_oval(x - 2, y - 2, x + 2, y + 2, fill='red')points.append((x,y))# 绘制连接线for i in range(len(points) - 1):canvas.create_line(points[i], points[i+1])def update_data_and_redraw(canvas):update_data() # 更新数据draw_chart(canvas, lis) # 重绘图表root.after(1000, update_data_and_redraw, canvas) # 每隔1000毫秒(1秒)调用一次该函数# 创建窗体和画布
root = tk.Tk()
root.title("动态数据展示")
canvas = tk.Canvas(root, width=600, height=400)
canvas.pack()update_data_and_redraw(canvas) # 开始数据更新和图形重绘的循环root.mainloop()
ser.close() # 捕获Ctrl+C中断信号后关闭串口