我正在尝试绘制从连接到Arduino的体重秤接收到的读数的图表。使用蓝牙的Arduino将数据发送到RPi,我成功制作了一个实时GUI。问题是,我正在尝试使用SpinBox或某种可以调整图形更新间隔的计数器。我已经尝试过在FuncAnimation中为间隔使用变量,但是它似乎不起作用。 我已被强行强行使用,并注意到一旦执行了代码,该间隔便设置为它接收并坚持的初始值。 while循环不能很好地实现我必须达到的目标。我也附上了下面的代码。请注意,我是Python的初学者。
import serial
from tkinter import *
from tkinter import ttk
from matplotlib import pyplot as plt
import matplotlib.animation as animation
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib import style
from matplotlib.figure import Figure
import time
import read_arduino
ser = serial.Serial('/dev/rfcomm0', 115200)
ser.flushInput()
root = Tk()
root.geometry('800x400+200+100')
root.title('This is my root window')
tab_control = ttk.Notebook(root)
tab1 = ttk.Frame(tab_control)
tab2 = ttk.Frame(tab_control)
tab_control.add(tab1, text='First')
tab_control.add(tab2, text='Second')
# var =IntVar()
# var.set(300)
# incr=1000
# spin = Spinbox(tab1, from_=200, to=1000, width=5, textvariable=var)
xar = [0]
yar = [0]
style.use('ggplot')
fig = plt.figure(figsize=(3, 2.5))
plt.xlabel("Time")
plt.ylabel("Weight")
ax1 = fig.add_subplot(1,1,1)
ax1.set_aspect("auto")
fig.subplots_adjust(wspace=0, hspace=0)
ax1.set_ylim(0, 100)
line, = ax1.plot(xar, yar, 'blue',marker='x')
plt.tight_layout()
dum= StringVar()
lbl = Label(tab1, textvariable=dum).grid(row=2,column=2)
def animate(i):
x=get_avg()
yar.append(x)
xar.append(i)
line.set_data(xar, yar)
ax1.set_xlim(0, i+1)
dum.set(x)
def get_avg():
n = 60
val=str(0.0)
for n in range(1,60):
val=str(ser.readline(),"utf-8").strip("\n")
return val
plotcanvas = FigureCanvasTkAgg(fig, tab1)
plotcanvas.get_tk_widget().grid(row=5,column=0)
ani = animation.FuncAnimation(fig, animate, interval=1000, blit=False)
tab_control.pack(expand=1, fill='both')
root.mainloop()