python
复制代码
import tkinter as tk
import random
import serial
lis=[]
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)/10
print("\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("程序已停止")
pass
def draw_chart(canvas, data):
canvas.delete("all") # 清除画布上的所有内容
# 以下是绘图代码,与之前相同,只是增加了canvas参数
margin = 40
width = 600 - 2 * margin
height = 400 - 2 * margin
x_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_scale
if 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_scale
canvas.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_scale
y = 400 - margin - (data[i] - 10) * y_scale
canvas.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中断信号后关闭串口