将matplotlib动画嵌入到tkinter框架中

use*_*454 5 python animation tkinter matplotlib python-embedding

对于一个项目,我正在研究一个简单的谐波运动模拟器(质量如何随时间振荡).我已经正确生成了数据并且已经在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()
Run Code Online (Sandbox Code Playgroud)

当取消注释plt.show()时,此代码将在tkinter框架中显示我想要的动画.我希望能够将该动画放在tkinter的框架内.

我也一直在matplotlib网站上查看所有的动画示例,但没有一个帮助过.我也在这个网站上查看了问题'21179971',并将tkinter按钮放在了pyplot图中,而我想把这个图放在一个tkinter框架内.

所以只是为了澄清一下,我希望能够在tkinter框架中取消注释"#plt.show()"时生成的动画,即(root = tk())

HYR*_*YRY 6

我修改了你的代码:

#---------Imports
from numpy import arange, sin, pi
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import Tkinter as Tk
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
#---------End of imports

fig = plt.Figure()

x = np.arange(0, 2*np.pi, 0.01)        # x-array

def animate(i):
    line.set_ydata(np.sin(x+i/10.0))  # update the data
    return line,

root = Tk.Tk()

label = Tk.Label(root,text="SHM Simulation").grid(column=0, row=0)

canvas = FigureCanvasTkAgg(fig, master=root)
canvas.get_tk_widget().grid(column=0,row=1)

ax = fig.add_subplot(111)
line, = ax.plot(x, np.sin(x))
ani = animation.FuncAnimation(fig, animate, np.arange(1, 200), interval=25, blit=False)

Tk.mainloop()
Run Code Online (Sandbox Code Playgroud)