Matplotlib: intentionally block code execution while waiting for a GUI event

Is there a way I can get matplotlib to block code execution until matplotlib.backend_bases.Event ?

I am working on some classes for interactively drawing lines and polygons inside matplotlib shapes, following these examples . What I really would like to do is execute the block until I finish editing my polygon and then get the end positions of the vertices - if you are familiar with MATLAB, I basically try to replicate the position = wait(roihandle) for example here .

I suppose I can set some class attribute of my interactive polygon object when a keystroke occurs, and then re-poll the object in my script to see if this event has occurred yet, but I was hoping it would be a more enjoyable way.

+6
source share
1 answer

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

Here is a simple example:

 from matplotlib import pyplot as plt class FigEventLoopDemo(object): def __init__(self): self.fig, self.ax = plt.subplots(1, 1, num='Event loop demo') self.clickme = self.ax.text(0.5, 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") self.fig.canvas.start_event_loop(timeout=-1) def on_pick(self, event): if event.artist is self.clickme: # exit the blocking event loop self.fig.canvas.stop_event_loop() print("now we're unblocked") 
+6
source

All Articles