0

I am plotting some figures one after each other (closing the windows, to see the next one), but i need a way to interrupt the cycle and finish the script by pressing a key ("Esc" for example).

I try using mscrt.getch(), but doesn't work, any advice would be appreciated.

The core cycle is something like this:

for i, _ in enumerate(ID_SECTION):
    FIG = plt.figure(
            num=ID_SECTION[i],
            figsize=(10, 7.5),
            facecolor='w'
        )
    curve = FIG.add_subplot(
            1, 2, 1,
            adjustable='box',
            aspect='equal'
        )
    curve.scatter(x, y)
    plt.show()
    plt.close('all')
mglasner
  • 75
  • 2
  • 9

1 Answers1

0

If you don't mind pressing 'enter' each loop to tell the loop to continue, you could add something like this to the end of your loop:

r = input("Continue [y]/n?")
if r == 'n':
    break

Otherwise, I think you'd have to add a keypress callback to your figures. Working from that example, something like this might work:

from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt

run = True

def press(event):
    global run
    if event.key == 'escape':
        run = False

Then add this to your loop:

FIG.canvas.mpl_connect('key_press_event', press)
if not run:
    break

Though, I'm not sure that adding a callback to a loop that creates figures is a good idea. It's probably better to create one figure and add the callback to that, then add a pause or something so that you can see what the figure creates each loop. But, if you're going to do that, the first input solution is probably better anyway.

Also note that I've used a global in the latter solution, which is generally frowned upon.

Community
  • 1
  • 1
farenorth
  • 10,165
  • 2
  • 39
  • 45