gpt4 book ai didi

python - 如何使用 mpl_disconnect() 重新获得控制权以结束 matplotlib 中的自定义 event_handling

转载 作者:行者123 更新时间:2023-11-30 22:58:10 25 4
gpt4 key购买 nike

当某些 GUI 完成输入输入时,我希望使用 mpl_disconnect() 函数重新获得控制权。我无法让 mpl_disconnect() 在我尝试过的任何情况下工作。

为了便于说明,我从 Matplotlib 文档中获取了有关事件处理的示例。该程序允许用户画一条线。我刚刚添加了三行代码(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()

按我的预期工作。

关于python - 如何使用 mpl_disconnect() 重新获得控制权以结束 matplotlib 中的自定义 event_handling,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36315634/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com