如何更新 tkinter Canvas 上的 matplotlib 子图?

我想更新嵌入到Canvastkinter GUI 中的子图。无论我尝试什么,我的意图都会失败。看看我有多远:


from tkinter import *

from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)

import matplotlib.pyplot as plt

import time


root = Tk()


figId = plt.figure()


canvas = FigureCanvasTkAgg(figId, master=root)

canvas.get_tk_widget().pack()

canvas.draw()


vals1 = [5, 6, 3, 9]

vals2 = vals1


for i in range(0, len(vals1)+1):

    toPlot = vals1[0:i]

    plt.subplot(211).plot(toPlot)

    plt.subplot(212).plot(toPlot)

    time.sleep(1)


root.mainloop()

我发现做类似的事情plt.pause(.1)不是正确的方法。对我来说,似乎我必须介绍matplotlib.animation,但我真的不知道该怎么做。


慕仙森
浏览 167回答 1
1回答

喵喵时光机

我找到了答案:import randomfrom itertools import countimport matplotlib.pyplot as pltfrom matplotlib.animation import FuncAnimationfrom tkinter import *from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)x_vals = []y_vals1 = []y_vals2 = []index = count()root = Tk()figId = plt.figure()canvas = FigureCanvasTkAgg(figId, master=root)canvas.get_tk_widget().pack()canvas.draw()def animate(i):    x_vals.append(next(index))    y_vals1.append(random.randint(0, 5))    y_vals2.append(random.randint(0, 5))    plt.cla()    plt.plot(x_vals, y_vals1)    plt.plot(x_vals, y_vals2)ani = FuncAnimation(plt.gcf(), animate, interval=1000)root.mainloop()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python