You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Matplotlib使用plt.connect采集鼠标轨迹点遇窗口自动关闭问题求助

问题原因

plt.disconnect()本身不会触发窗口关闭,本质原因是plt.pause(5)执行结束后,程序没有后续的阻塞逻辑维持matplotlib的GUI事件循环,执行完所有代码后进程自动退出,绘图窗口随之被销毁。另外你新增点绘制逻辑后没有主动刷新画布,就算窗口保留也无法看到新绘制的轨迹。

修复后代码

import matplotlib.pyplot as plt
import numpy as np
t = np.arange(0.0, 1.0, 0.01)
s = np.sin(2 * np.pi * t) 
fig, ax = plt.subplots()
ax.plot(t, s)  # 绘制初始曲线
x=[]
y=[]
def on_move(event):
    global x,y
    if event.inaxes:
        x.append(event.xdata)
        y.append(event.ydata)
        print('data coords %f %f' % (event.xdata, event.ydata))

plt.waitforbuttonpress()
binding_id = plt.connect('motion_notify_event', on_move)
plt.pause(5)  # 留5秒采集鼠标轨迹
plt.disconnect(binding_id) # 解绑鼠标移动事件,不再采集坐标

# 核心改动
ax.plot(x, y, c='red') # 绘制采集到的轨迹,指定红色方便和初始曲线区分
fig.canvas.draw_idle() # 手动刷新画布,渲染新绘制的内容
plt.show() # 阻塞维持GUI事件循环,窗口不会自动关闭,手动关闭窗口后程序才会结束

补充说明

  • 如果需要在关闭窗口前执行更多操作,可以在plt.show()前添加其他逻辑,只要plt.show()未执行,窗口都会保持响应状态
  • 原代码中未使用的MouseButton导入可以删除,不影响逻辑运行

内容的提问来源于stack exchange,提问作者Erasmo Trentin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 12:27:03