Question

I want to pause my python script while I wait for a user to press enter - while the focus is on a matplotlib figure.

I tried the following code, but the script binds up the the event handling when it goes into the wile loop. Making it so the user is unable to draw the rectangle.

class DrawRectangle:

    def __init__(self, image):
        self.waiting_for_entry = True
        '''
        Event handling that lets user draw a rectangle on an image. 
        when the user is done drawing they press "enter" to disconnect the canvas
        '''

    def on_key_press(self, event):
        if event.key == 'enter':
            '''
            disconnect event handling
            '''
            self.waiting_for_entry = False

    def return_image_inside(self):
        '''
        Return the portion of the image inclosed in the rectangle
        '''

if __name__ == "__main__":
    image = import_some_image() # import an image
    image_plot = plt.imshow(image)
    selector = DrawRectangle(image_plot)

    while selector.waiting_for_entry:
        pass

    working_data = selector.return_image_inside()

    '''
    do stuff with selected image
    '''

Pausing the program with something like

print "press enter to continue:"
raw_input()

Does work, but requires the user to return focus to the terminal screen, then press enter.

Any recommendations on how to pause the script until an event is registered in matplotlib?

Was it helpful?

Solution

I think you'll have to implement a simple (single window) GUI and include a matplotlib graphical backend inside that.

You might be in luck: the matplotlib examples provide a nice example. Note how, when running the example, keypresses are caught and printed to the terminal, but also forwarded to matplotlib.backend_bases.key_press_handler.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top