python - 将 matplotlib 动画嵌入到 tkinter 框架中

标签 python animation matplotlib tkinter 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()

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

我也去过 matplotlib 网站并查看了所有动画示例,但没有一个有帮助。我也看过Embedding an animated matplotlib in tk并且已将 tkinter 按钮放置在 pyplot 图形中,而我想将图形放置在 tkinter 框架中。

所以澄清一下,我希望能够将 plt.show() 未注释时生成的动画放置在 tkinter 框架中,即 root = tk().

最佳答案

我修改了你的代码:

#---------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()

关于python - 将 matplotlib 动画嵌入到 tkinter 框架中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21197728/

相关文章:

python - 用 Pandas 和 Group By 绘制堆叠直方图

python JSON 到 dict 检查是否是单个或多个 child

iphone - Windows Phone 7 UI (Metro) 可以在 iOS 上使用吗?

ios - drawRect :? 之后有没有直接调用的方法

java - 动画中的过渡帧

python - 如何用 True、False 和颜色编码 Python 绘图来标记 Y 轴?

python - 将旋转矩阵应用于 xy 坐标

python - 使用 python gdata.contacts.client 检索一个联系人

python - 如何通过 Selenium 和 Python 将文本按照 html 发送到文本区域

python - 更新与其他数据相同的行中的数据