简体   繁体   English

在wxpython gui中,matplotlib动画不会更新,但可以独立运行

[英]matplotlib animation does not update when in wxpython gui but works standalone

I have a wxPython GUI in which I use matplotlib for 2D and 3D graphics. 我有一个wxPython GUI,其中我将matplotlib用于2D和3D图形。

I was having problems getting a surface plot to animate, so I used the following dummy case adapted from someplace online to test. 我在获取曲面图以进行动画处理时遇到了问题,因此我使用了以下从网上某个地方改编的虚拟机壳进行测试。 It is a fairly typical example for 3D animation and works fine when run standalone. 这是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()

The "True" test is of course unnecessary but was meant to replicate something like the structure in the GUI at the point of execution (to check for any scoping issues). 当然,“ True”测试不是必需的,但它旨在在执行时在GUI中复制类似结构的内容(以检查任何范围确定问题)。

When I insert the exact same code into my GUI with a wx.Button causing execution of the code, it plots only the first frame and nothing else, but doesn't issue any error either (running inside IDLE). 当我使用一个导致执行代码的wx.Button将完全相同的代码插入到我的GUI中时,它仅绘制第一帧而没有其他内容,但是也不会发出任何错误(在IDLE中运行)。 I can verify by printing that exactly one (the first iteration i=0 ) frame is plotting. 我可以通过打印来确认正在绘制一个(第一迭代i=0 )帧。

This is exactly the behavior also of the actual data of interest which originated the problem. 这正是引起问题的实际感兴趣数据的行为。

Thank you. 谢谢。

When using an animation inside of a GUI class, make sure to keep the reference to the animation object in a class member so that it doesn't get garbage collected at the end of the method in which it is created. 在GUI类中使用动画时,请确保将对动画对象的引用保留在类成员中,以免在创建该对象的方法结束时收集到垃圾。 Using something like 使用类似

self.ani = animation.FuncAnimation(....

rather than 而不是

ani = animation.FuncAnimation(....

should work. 应该管用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM