我正在开发一个简单的谐振模拟器,用于模拟物体随时间振动的情况。目前已经成功获取了数据,并在tkinter框架内绘制出了静态图形。但是,我的目标是将其显示为随时间变化的动画。
为了方便起见,我使用以下代码创建了一个程序的模型:
#---------Imports
from numpy import arange, sin, pi
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import tkinter as Tk
from tkinter import ttk
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
#---------End of imports
fig, ax = plt.subplots()
x = np.arange(0, 2*np.pi, 0.01) # x-array
line, = ax.plot(x, np.sin(x))
def animate(i):
line.set_ydata(np.sin(x+i/10.0)) # update the data
return line,
ani = animation.FuncAnimation(fig, animate, np.arange(1, 200), interval=25, blit=False)
#plt.show() #What I want the object in tkinter to appear as
root = Tk.Tk()
label = ttk.Label(root,text="SHM Simulation").grid(column=0, row=0)
canvas = FigureCanvasTkAgg(fig, master=root)
canvas.show()
canvas.get_tk_widget().grid(column=0,row=1)
Tk.mainloop()
这段代码将在tkinter框架中显示所需的动画,当plt.show()
被取消注释时。我希望能够将该动画嵌入到tkinter框架中。我已经查看了matplotlib网站上的所有动画示例,但都没有帮助。我还在Embedding an animated matplotlib in tk上查询过,但那个把tkinter按钮置于pyplot图形之内,我想要把图形放在tkinter框架里面。所以,为澄清起见,我想将plt.show()
产生的动画放置在一个tkinter框架中,即root = tk()
。