matplotlib: deliberately block code execution pending a GUI event

爱⌒轻易说出口 提交于 2019-12-09 16:50:36

问题


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

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.


回答1:


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, 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")


来源:https://stackoverflow.com/questions/14325844/matplotlib-deliberately-block-code-execution-pending-a-gui-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!