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

Matplotlib中鼠标进入Axes时如何设置焦点触发按键事件?

Matplotlib中鼠标进入Axes时自动获取键盘焦点的问题

我在Matplotlib中绑定了key_press事件,但必须先点击图表才会触发。希望实现鼠标进入Axes区域时,自动让键盘焦点落在Axes上。

尝试相关方案时出现以下错误:

AttributeError: 'Canvas' object has no attribute 'setFocus'

我编写的事件处理函数如下:

def on_enter(self, event):
    # self.fig.canvas.setFocus()
    event.canvas.setFocus()

无论是通过事件对象还是已存储的figure对象引用canvas,都会报相同的错误。

系统环境

  • MAC OS Sonoma 14.3
  • 在Jupyter Notebook中使用%matplotlib widget
  • 后端为ipympl.backend_nbagg
  • 使用ipywidgets作为GUI控件

事件绑定代码

self.cid_enter = self.fig.canvas.mpl_connect('axes_enter_event', self.on_enter)

另外,调用dir()查看Canvas对象的属性时,发现它包含focus属性,但没有setFocus方法。

内容的提问来源于stack exchange,提问作者Paul Chernoch

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 01:33:14