[英]Embedding matplotlib canvas into tkinter GUI - plot is not showing up, but no error is thrown
[英]Embedding Matplotlib live plot data from Arduino in tkinter canvas
我才使用 Python 幾個星期。 我可以毫無問題地使用 Matplotlib 繪制來自 Arduino 的數據。 然而,該圖顯示為一個彈出窗口,我希望該圖僅顯示在我使用 tkinter 制作的 GUI 的根窗口中的畫布中。 我嘗試了多種組合,但無法正常工作。 如果我只是將繪圖值添加到代碼中,比方說:
a.plot([1, 2, 3, 4, 5], [2, 3, 4, 5, 6, 7])
它工作正常,所以我的主要問題是從 Arduino 獲取數據時的 while 循環。 我也嘗試了 drawnow 選項來更新情節,但我得到了完全相同的結果。 無論我做什么,我似乎都無法從中獲取情節以停止顯示為單獨的窗口。
后面帶有主 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()
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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.