Getting blitting to work in funcAnimation embedded in PyQT4 GUI

后端 未结 2 963
独厮守ぢ
独厮守ぢ 2021-01-13 19:55

Starting with the working Matplotlib animation code shown below, my goal is to embed this animation (which is just a circle moving across the screen) within a PyQT4 GUI.

2条回答
  •  无人共我
    2021-01-13 20:24

    After looking at the source code of the animation module, I realized that there is an error in the Animation class (the dictionary bg_cache is empty, when it is accessed for the first time with blitting switched on).

    This is fixed in the git version of matplotlib; however, in the most recent stable version 1.5.1, the bug is still present. You can either fix the bug in the matplotlib code itself or you can make a subclass to FuncAnimation. I chose that way, because it should still work after updating matplotlib.

    from matplotlib import animation
    
    class MyFuncAnimation(animation.FuncAnimation):
        """
        Unfortunately, it seems that the _blit_clear method of the Animation
        class contains an error in several matplotlib verions
        That's why, I fork it here and insert the latest git version of
        the function.
        """
        def _blit_clear(self, artists, bg_cache):
            # Get a list of the axes that need clearing from the artists that
            # have been drawn. Grab the appropriate saved background from the
            # cache and restore.
            axes = set(a.axes for a in artists)
            for a in axes:
                if a in bg_cache: # this is the previously missing line
                    a.figure.canvas.restore_region(bg_cache[a])
    

    Then, simpy use MyFuncAnimation instead of animation.FuncAnimation.

    Took me a while to figure it out, but I hope it helps anybody.

提交回复
热议问题