我正在尝试使用canvas在tkinter网格上显示两个实时更新的matplotlib图形。
我目前已经在spyder上使用python 3.7尝试了以下代码。
a = Figure(figsize=(10, 3))
plot_a = a.add_subplot(111)
plot_a.set_xlim([0, 2*np.pi])
plot_a.set_ylim([-1, 1])
lna, = plot_a.plot([], [], color='red', lw=5)
b = Figure(figsize=(10, 3))
plot_b = b.add_subplot(111)
plot_b.set_xlim([0, 2*np.pi])
plot_b.set_ylim([-1, 1])
lnb, = plot_b.plot([], [], color='olive', lw=5)
x = np.linspace(0, 2*np.pi, 1024)
def updateGraphsA(i):
lna.set_xdata(x)
lna.set_ydata(np.sin(x + i * np.pi / 10))
print('in A')
def updateGraphsB(i):
lnb.set_xdata(x)
lnb.set_ydata(np.sin(x - i * np.pi / 10))
print('in B')
class GUI(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
tk.Tk.wm_title(self, "Placeholder")
canvasA = FigureCanvasTkAgg(a, self)
canvasA.draw()
canvasA.get_tk_widget().grid(
row=0, column=0, pady=2, padx=10, sticky='nsew')
canvasB = FigureCanvasTkAgg(b, self)
canvasB.draw()
canvasB.get_tk_widget().grid(
row=1, column=0, pady=2, padx=10, sticky='nsew')
app = GUI()
aniA = animation.FuncAnimation(a, updateGraphsA, interval=1000, blit=False)
aniB = animation.FuncAnimation(b, updateGraphsB, interval=1000, blit=False)
app.mainloop()
我希望在更新GUI上的两个图形时,这将在打印“ a”和“ b”之间交替进行。但是,它仅打印“ in b”,并且仅更新canvas / graph B
如果我在画布B的类中注释掉以下代码,
canvasB = FigureCanvasTkAgg(b, self)
canvasB.draw()
canvasB.get_tk_widget().grid(
row=1, column=0, pady=2, padx=10, sticky='nsew')
它将打印出“ a”并按预期更新画布/图形A。如何解决此问题,以便同时更新两者。