2

I use the following code to stop/resume animation (either ArtistAnimation or FuncAnimation works fine):

def keypress(event):
    global anim_running
    if event.key == ' ': # SPACE: pause and resume animation
        if anim and anim.event_source:
            anim.event_source.stop() if anim_running else anim.event_source.start()
            anim_running ^= True

fig.canvas.mpl_connect('key_press_event', keypress)

Now, what I would like to do is, with the animation stopped I would like to press some key (e.g. 't') and see the next frame and with some other key (e.g. 'T') see the previous frame. I.e. to be able to manually step frame by frame.

The full code of the program is here (but it is not necessary for answering the question):

https://github.com/tigran123/quantum-infodynamics/blob/master/dynamics/solplay.py

I realise, of course that one could completely ignore the 'k' argument of animate(k) and maintain my own global frame number which could be controlled via keyboard handler. But this would waste a lot of CPU (i.e. keep re-rendering the same frame) and I thought there must be a better way by manipulating the animation object directly.

Tigran Aivazian
  • 342
  • 3
  • 11
  • I discovered one way of doing this, namely calling ani.event_source.stop() from the animate() function, see the example here: https://github.com/tigran123/quantum-infodynamics/blob/master/classical-mechanics/pendulum/psim.py – Tigran Aivazian Nov 19 '17 at 10:28
  • [This question](https://stackoverflow.com/questions/44985966/managing-dynamic-plotting-in-matplotlib-animation-module) might be useful here. Its answer allows to play an animation step by step using a button, but it should be easily adaptable to also allow for a key_press event. – ImportanceOfBeingErnest Nov 20 '17 at 23:07
  • Thank you, brother --- actually I've noticed your wonderful Player class yesterday and started playing with it and learning how it works today. I just couldn't leave a comment about it on that thread because my reputation isn't high enough to allow that, apparently. – Tigran Aivazian Nov 20 '17 at 23:42

0 Answers0