在 tkinter 画布中嵌入来自 Arduino 的 Matplotlib 实时绘图数据

W. *_*Riv 6 python canvas tkinter arduino matplotlib

我才使用 Python 几个星期。我使用 Matplotlib 绘制来自 Arduino 的数据没有任何问题。然而,该图显示为弹出窗口,我希望该图仅显示在我用 tkinter 制作的 GUI 根窗口的画布中。我尝试了多种组合,但无法使其发挥作用。如果我只是将绘图值添加到代码中,可以这样说:

a.plot([1, 2, 3, 4, 5], [2, 3, 4, 5, 6, 7])
Run Code Online (Sandbox Code Playgroud)

它工作得很好,所以我的主要问题是从 Arduino 获取数据时的 while 循环。我还尝试了drawow选项来更新绘图,但我得到了相同的确切结果。无论我做什么,我似乎都无法让情节停止显示为单独的窗口。

后面带有主 GUI 窗口的绘图窗口:

绘图窗口,主 GUI 窗口位于后面

这是我正在使用的示例代码:

import serial
from tkinter import *
import numpy as np
from matplotlib import pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg


root = Tk()
root.geometry('1200x700+200+100')
root.title('This is my root window')
root.state('zoomed')
root.config(background='#fafafa')


yar = []
plt.ion()
style.use('ggplot')
fig = plt.figure(figsize=(14, 4.5), dpi=100)
ax1 = fig.add_subplot(1, 1, 1)
ser = serial.Serial('com3', 9600)

def animate(i):
    while True:
        ser.reset_input_buffer()
        data = ser.readline().decode("utf-8")
        data_array = data.split(',')
        yvalue = float(data_array[1])
        yar.append(yvalue)
        print(yvalue)
        plt.ylim(0, 100)
        ax1.plot(yar, 'r', marker='o')
        plt.pause(0.0001)


plotcanvas = FigureCanvasTkAgg(fig, root, animate)
plotcanvas.get_tk_widget().grid(column=1, row=1)
ani = animation.FuncAnimation(fig, animate, interval=1000, blit=True)
plotcanvas.show()

root.mainloop()
Run Code Online (Sandbox Code Playgroud)

Imp*_*est 6

tk 的主循环将处理动画,因此您不应使用 plt.ion() 或 plt.pause()。

动画函数将每秒调用一次interval。您不能在该函数内使用while True循环。

没有任何理由向FigureCanvasTkAgg.

blit=True除非您知道自己在做什么,否则请勿使用。对于一秒的间隔来说,这是没有必要的。

更新该线,而不是在每个迭代步骤中重新绘制它。

#import serial
from Tkinter import *
from matplotlib import pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg


root = Tk()
root.geometry('1200x700+200+100')
root.title('This is my root window')
root.state('zoomed')
root.config(background='#fafafa')

xar = []
yar = []

style.use('ggplot')
fig = plt.figure(figsize=(14, 4.5), dpi=100)
ax1 = fig.add_subplot(1, 1, 1)
ax1.set_ylim(0, 100)
line, = ax1.plot(xar, yar, 'r', marker='o')
#ser = serial.Serial('com3', 9600)

def animate(i):
    #ser.reset_input_buffer()
    #data = ser.readline().decode("utf-8")
    #data_array = data.split(',')
    #yvalue = float(data_array[1])
    yar.append(99-i)
    xar.append(i)
    line.set_data(xar, yar)
    ax1.set_xlim(0, i+1)


plotcanvas = FigureCanvasTkAgg(fig, root)
plotcanvas.get_tk_widget().grid(column=1, row=1)
ani = animation.FuncAnimation(fig, animate, interval=1000, blit=False)

root.mainloop()
Run Code Online (Sandbox Code Playgroud)