ali_m ali_m - 1 year ago 184
Python Question

matplotlib: deliberately block code execution pending a GUI event

Is there some way that I can get matplotlib to block code execution pending a


I've been working on some classes for interactively drawing lines and polygons inside matplotlib figures, following these examples. What I'd really like to do is block execution until I'm done editing my polygon, then get the final positions of the vertices - if you're familiar with MATLAB, I'm basically trying to replicate the
position = wait(roihandle)
syntax, for example here.

I suppose I could set some class attribute of my interactive polygon object when a keypress occurs, then repeatedly poll the object in my script to see if the event has occurred yet, but I was hoping there would be a nicer way.

Answer Source

Well, that was easier than I thought it would be! For those who are interested I found a solution using figure.canvas.start_event_loop() and figure.canvas.stop_event_loop().

Here's a simple example:

from matplotlib import pyplot as plt

class FigEventLoopDemo(object):

    def __init__(self):

        self.fig, = plt.subplots(1, 1, num='Event loop demo')
        self.clickme =, 0.5, 'click me',
                                    ha='center', va='center',
                                    color='r', fontsize=20, picker=10)

        # add a callback that triggers when the text is clicked
        self.cid = self.fig.canvas.mpl_connect('pick_event', self.on_pick)

        # start a blocking event loop
        print("entering a blocking loop")

    def on_pick(self, event):

        if event.artist is self.clickme:

            # exit the blocking event loop
            print("now we're unblocked")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download