matplotlib:在GUI事件之前故意阻止代码执行 [英] matplotlib: deliberately block code execution pending a GUI event
问题描述
有没有办法让matplotlib阻止代码执行等待一个 matplotlib.backend_bases.Event
?
Is there some way that I can get matplotlib to block code execution pending a matplotlib.backend_bases.Event
?
我一直在研究一些类,以便在matplotlib数据中交互地绘制线条和多边形,遵循这些例子一>。我真正想要做的是阻止执行,直到我完成编辑多边形,然后获得顶点的最终位置 - 如果你熟悉MATLAB,我基本上是试图复制 position = wait(roihandle)
语法,例如这里。
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.
推荐答案
那很简单比我以为会是!对于有兴趣的人,我使用 figure.canvas.start_event_loop()
和 figure.canvas.stop_event_loop()
。
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()
.
这是一个简单的例子:
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")
这篇关于matplotlib:在GUI事件之前故意阻止代码执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!