如何在Jupyter Lab中插入图片?求适配Lab的替代代码
在Jupyter Lab中插入图片的可行代码方案
你提到的那段ipywidgets代码在Jupyter Lab里失效,大概率是因为Lab对widgets的依赖配置和Notebook略有不同,下面给你两种靠谱的解决办法:
方法一:修复IPyWidgets的使用方式
首先确保你已经安装了ipywidgets的Lab扩展(如果没装的话,先运行下面的命令):
pip install ipywidgets jupyter labextension install @jupyter-widgets/jupyterlab-manager
之后就可以用类似的代码,简化后如下(注意确保文件路径正确):
import ipywidgets as widgets with open("./image.png", "rb") as file: image_data = file.read() widgets.Image( value=image_data, format='png', width=700, height=100 )
如果还是无法渲染,重启一下Jupyter Lab就能正常生效了。
方法二:用Python原生的display模块(更简单通用)
要是不想折腾widgets扩展,也可以用IPython.display里的Image类,这种方式在Notebook和Lab里都能正常运行,代码还更简洁:
from IPython.display import Image Image(filename='./image.png', width=700, height=100)
内容的提问来源于stack exchange,提问作者baxx
相关产品推荐
相关产品推荐

