Python 如何在matplotlib中使用mpl_disconnect()结束自定义事件处理来重新获得控制
我希望使用mpl_disconnect()函数在某个GUI获得输入后重新获得控制权。我无法让mpl_disconnect()在我尝试过的任何情况下工作 为了进行说明,我从Matplotlib文档中获取了这个关于事件处理的示例。这个程序允许用户画一条线。 我刚刚添加了三行代码(Python 如何在matplotlib中使用mpl_disconnect()结束自定义事件处理来重新获得控制,python,matplotlib,Python,Matplotlib,我希望使用mpl_disconnect()函数在某个GUI获得输入后重新获得控制权。我无法让mpl_disconnect()在我尝试过的任何情况下工作 为了进行说明,我从Matplotlib文档中获取了这个关于事件处理的示例。这个程序允许用户画一条线。 我刚刚添加了三行代码(if event.button==3…)。因此,当用户单击鼠标右键时,处理程序应该退出 from matplotlib import pyplot as plt class LineBuilder: def __i
if event.button==3
…)。因此,当用户单击鼠标右键时,处理程序应该退出
from matplotlib import pyplot as plt
class LineBuilder:
def __init__(self, line):
self.line = line
self.xs = list(line.get_xdata())
self.ys = list(line.get_ydata())
self.cid = line.figure.canvas.mpl_connect('button_press_event', self)
def __call__(self, event):
print 'click', event
if event.button==3:
event.canvas.mpl_disconnect(event.canvas.manager.key_press_handler_id)
return
if event.inaxes!=self.line.axes: return
self.xs.append(event.xdata)
self.ys.append(event.ydata)
self.line.set_data(self.xs, self.ys)
self.line.figure.canvas.draw()
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_title('click to build line segments')
line, = ax.plot([0], [0]) # empty line
linebuilder = LineBuilder(line)
plt.show()
print("I'm back!")
我的经验是,在我点击右键(这不会延长线)后,程序不会停止。相反,我可以用鼠标左键继续构建线
如何断开事件处理程序?
更新:。。。并重新获得控制权,例如获得最终打印报表
from matplotlib import pyplot as plt
class LineBuilder:
def __init__(self, line):
self.line = line
self.xs = list(line.get_xdata())
self.ys = list(line.get_ydata())
self.cid = line.figure.canvas.mpl_connect('button_press_event', self)
def __call__(self, event):
print('click', vars(event))
if event.button==3:
print('clean up')
event.canvas.mpl_disconnect(self.cid)
return
if event.inaxes != self.line.axes:
return
self.xs.append(event.xdata)
self.ys.append(event.ydata)
self.line.set_data(self.xs, self.ys)
self.line.figure.canvas.draw_idle()
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_title('click to build line segments')
line, = ax.plot([0], [0]) # empty line
linebuilder = LineBuilder(line)
plt.show()
正如我预期的那样工作。我想您应该使用
mpl\u disconnect(self.cid)
?这样做更好,但仍然无法将控制权返回到我的代码(“我回来了”)。(还有,为什么按键\u press\u handler\u id与self.cid不同?)这是因为plt.show
仍处于阻塞状态。当您关闭窗口,GUI事件循环停止运行时,您将重新获得控制权。key\u press\u handler\u id
是(iirc)默认按键处理程序的id('k','l'表示日志,'ctrl-w'表示退出,等等),这是使用self.cid
而不是event.canvas.manager.key\u press\u handler\u id
的唯一区别?