【发布时间】:2017-06-30 17:38:06
【问题描述】:
我只用了几个星期的 Python。我用 Matplotlib 绘制来自 Arduino 的数据没有问题。但是,该图显示为一个弹出窗口,我希望该图仅显示在我使用 tkinter 制作的 GUI 的根窗口中的画布中。我已经尝试了多种组合,但我无法让它发挥作用。如果我只是将绘图值添加到代码中,假设:
a.plot([1, 2, 3, 4, 5], [2, 3, 4, 5, 6, 7])
它工作正常,所以我的主要问题是从 Arduino 获取数据时的 while 循环。我也尝试过 drawow 选项来更新绘图,但我得到了相同的确切结果。无论我做什么,我似乎都无法让情节停止显示为一个单独的窗口。
绘图窗口和主 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()
【问题讨论】:
标签: python canvas matplotlib tkinter arduino