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

JupyterLab按钮事件失效求助:代码在Jupyter Notebook可正常运行

JupyterLab中ipywidgets按钮无响应的解决方案

问题描述

以下代码在Jupyter Notebook中可正常运行,但在JupyterLab中点击按钮无响应:

import ipywidgets as widgets
from IPython.display import display
button = widgets.Button(description="Click Me!")
display(button)
def on_button_clicked(b):
    print("Button clicked.")
button.on_click(on_button_clicked)

环境信息:MacOsX 10.12.2,Python 2.7.14 :: Anaconda, Inc.,Jupyter Notebook 5.4.0,Jupyter Lab 0.31.5

解决步骤

针对你使用的旧版本JupyterLab(0.31.5),核心问题是它默认不支持ipywidgets组件,需要手动配置扩展来解决,具体操作如下:

  • 安装并构建ipywidgets的JupyterLab扩展
    打开终端,依次运行这两个命令:

    jupyter labextension install @jupyter-widgets/jupyterlab-manager
    jupyter lab build
    

    注意:这个过程依赖Node.js的npm工具,如果终端提示找不到npm,你需要先安装兼容Python 2.7的Node.js版本(推荐Node.js 12.x系列,更高版本可能和你的Python 2.7环境不兼容)。

  • 匹配兼容的ipywidgets版本
    JupyterLab 0.31.5和高版本ipywidgets存在兼容性问题,建议安装7.x系列的ipywidgets,执行:

    pip install ipywidgets==7.7.1
    

    安装完成后,重新运行一遍上面的扩展安装和build命令。

  • 启用扩展并重启JupyterLab
    重启JupyterLab后,打开命令面板(Mac上按Cmd+Shift+C),输入Widget Manager: Enable并执行,确保部件管理器处于启用状态。也可以通过左侧栏的“扩展”标签,确认@jupyter-widgets/jupyterlab-manager已经被启用。

  • 清空缓存(若上述步骤无效)
    有时候缓存会干扰扩展加载,关闭JupyterLab后,在终端执行:

    rm -rf ~/.jupyter/lab
    

    然后重新启动JupyterLab,它会自动重新构建缓存文件。

内容的提问来源于stack exchange,提问作者4givN

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:29:52