matplotlib 动画在 wxpython gui 中不更新但独立工作
matplotlib animation does not update when in wxpython gui but works standalone
我有一个 wxPython GUI,我在其中使用 matplotlib 处理 2D 和 3D 图形。
我在制作曲面图动画时遇到了问题,所以我使用了以下从网上某处改编的虚拟案例进行测试。这是一个相当典型的 3D 动画示例,并且在 运行 独立时工作正常。
if True:
from mpl_toolkits.mplot3d import axes3d
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
def generate(X, Y, phi):
R = 1 - np.sqrt(X**2 + Y**2)
return np.cos(2 * np.pi * X + phi) * R
fig = plt.figure()
ax = axes3d.Axes3D(fig)
xs = np.linspace(-1, 1, 3)
ys = np.linspace(-1, 1, 3)
X, Y = np.meshgrid(xs, ys)
Z = generate(X, Y, 0.0)
wframe = ax.plot_wireframe(X, Y, Z, rstride=2, cstride=2)
ax.set_zlim(-1,1)
def update(i, ax, fig):
print i
ax.cla()
phi = i * 360 / 2 / np.pi / 100
Z = generate(X, Y, phi)
wframe = ax.plot_wireframe(X, Y, Z, rstride=2, cstride=2)
ax.set_zlim(-1,1)
return wframe
ani = animation.FuncAnimation(fig, update,
frames=xrange(100),
fargs=(ax, fig), interval=100)
plt.show()
"True" 测试当然是不必要的,但它是为了在执行时复制类似 GUI 中的结构的东西(以检查任何范围问题)。
当我使用 wx.Button 将完全相同的代码插入到我的 GUI 中导致代码执行时,它只绘制第一帧而不绘制其他任何内容,但也不会发出任何错误(运行宁内空闲)。我可以通过打印确实有一个(第一次迭代 i=0
)帧正在绘制来验证。
这也正是引起问题的感兴趣的实际数据的行为。
谢谢。
在 GUI class 中使用动画时,请确保在 class 成员中保留对动画对象的引用,以免在创建它的方法。使用像
这样的东西
self.ani = animation.FuncAnimation(....
而不是
ani = animation.FuncAnimation(....
应该可以。
我有一个 wxPython GUI,我在其中使用 matplotlib 处理 2D 和 3D 图形。
我在制作曲面图动画时遇到了问题,所以我使用了以下从网上某处改编的虚拟案例进行测试。这是一个相当典型的 3D 动画示例,并且在 运行 独立时工作正常。
if True:
from mpl_toolkits.mplot3d import axes3d
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
def generate(X, Y, phi):
R = 1 - np.sqrt(X**2 + Y**2)
return np.cos(2 * np.pi * X + phi) * R
fig = plt.figure()
ax = axes3d.Axes3D(fig)
xs = np.linspace(-1, 1, 3)
ys = np.linspace(-1, 1, 3)
X, Y = np.meshgrid(xs, ys)
Z = generate(X, Y, 0.0)
wframe = ax.plot_wireframe(X, Y, Z, rstride=2, cstride=2)
ax.set_zlim(-1,1)
def update(i, ax, fig):
print i
ax.cla()
phi = i * 360 / 2 / np.pi / 100
Z = generate(X, Y, phi)
wframe = ax.plot_wireframe(X, Y, Z, rstride=2, cstride=2)
ax.set_zlim(-1,1)
return wframe
ani = animation.FuncAnimation(fig, update,
frames=xrange(100),
fargs=(ax, fig), interval=100)
plt.show()
"True" 测试当然是不必要的,但它是为了在执行时复制类似 GUI 中的结构的东西(以检查任何范围问题)。
当我使用 wx.Button 将完全相同的代码插入到我的 GUI 中导致代码执行时,它只绘制第一帧而不绘制其他任何内容,但也不会发出任何错误(运行宁内空闲)。我可以通过打印确实有一个(第一次迭代 i=0
)帧正在绘制来验证。
这也正是引起问题的感兴趣的实际数据的行为。
谢谢。
在 GUI class 中使用动画时,请确保在 class 成员中保留对动画对象的引用,以免在创建它的方法。使用像
这样的东西self.ani = animation.FuncAnimation(....
而不是
ani = animation.FuncAnimation(....
应该可以。