How to pause a pylab figure until a key is pressed or a mouse is pressed?

I am trying to program an animated simulation using pylab and networkx. The simulation is not interesting all the time, so most of the time I want it to go fast, however I want it to be able to pause it and look at it when it looks interesting. Pausing the screen until pressing a key solves my problem, because I can press a key as quickly / slowly as I want.

Here is an example of a situation:

import numpy as np import networkx as nx import pylab as plt import sys def drawGraph(matrix): plt.clf() G = nx.DiGraph(np.array(matrix)) nx.draw_networkx(G) plt.draw() plt.pause(1) #I want this pause to be replaced by a keypress #so that it pauses as long as I want A=[[0,1],[1,0]] B=[[0,1],[0,0]] x=1 while True: if x==1: drawGraph(A) x=0 else: drawGraph(B) x=1 

How can I rewrite the line plt.pause (1) so that the program pauses until a key is pressed?

Some approaches suggested in other threads pause the program, but the image disappears or is not updated.

+6
source share
3 answers

The following code stops and restarts with a mouse click. It uses the "TKAgg" backend:

 import numpy as np import networkx as nx import matplotlib matplotlib.use("TkAgg") import pylab as plt plt.ion() fig = plt.figure() pause = False def onclick(event): global pause pause = not pause fig.canvas.mpl_connect('button_press_event', onclick) def drawGraph(matrix): fig.clear() G = nx.DiGraph(np.array(matrix)) nx.draw_networkx(G) plt.draw() A=[[0,1],[1,0]] B=[[0,1],[0,0]] x=1 while True: if not pause: if x==1: drawGraph(A) x=0 else: drawGraph(B) x=1 fig.canvas.get_tk_widget().update() # process events 
+8
source

Is there any reason not to use waitforbuttonpress ()?

 import matplotlib.pyplot as plt A=[[0,1],[1,0]] B=[[0,1],[0,0]] x=1 while True: if x==1: drawGraph(A) x=0 else: drawGraph(B) x=1 plt.waitforbuttonpress() 

That being said, wait for the key or button to press for something to happen. It returns values ​​if you want to know more about the event. Very easy.

+33
source

You can wait while the user presses the enter key with raw_input() .

To display graphs after import, add plt.ion() .

I don't think there is a simple simple platform-independent way to wait for a keypress in Python, but you can check this if Enter is not enough.

+2
source

All Articles