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

标签 python matplotlib

当某些 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/

相关文章:

python - 从 matplotlib 导入 ft2font : "ImportError: DLL load failed: The specified procedure could not be found."

python - Spark mllib 线性回归给出非常糟糕的结果

python - 帮助构建一对多关系的 GQL 查询

python - pyglet 的形状或场景管理?

python - BeautifulSoup 删除嵌套标签

python - 使用 matplotlib + errorbar 进行动画

javascript - 为什么请求无法访问该网站的安全页面?

python - 如何将 Seaborn 图集成到 Tkinter GUI 中

python - 如何标注图中每条线的最高点?

python - 如何在 Seaborn/Matplotlib 中将所有边缘颜色设置为无?