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

VS Code中使用pyqtgraph绘图遇Jupyter单元格冻结问题求解

解决pyqtgraph在VS Code Jupyter单元格中冻结的问题

问题原因

直接调用pg.image()会启动独立的Qt GUI窗口,但Jupyter环境的事件循环与Qt的GUI事件循环存在冲突,导致单元格无响应、冻结。

可行解决方案

方案1:启用Qt事件循环集成

在运行绘图代码前,先执行IPython魔法命令%gui qt,让Jupyter与Qt事件循环兼容:

# %%
%gui qt
import pyqtgraph as pg
import numpy as np

x = np.linspace(0,10)
y = np.linspace(0,10)
X, Y = np.meshgrid(x, y)
img = np.sin(X)*np.sin(Y)
pg.image(img)

执行后会弹出独立的Qt窗口显示图像,单元格不会冻结。

方案2:使用pyqtgraph的Jupyter Widget后端

如果希望图像直接嵌入在Jupyter单元格中(而非弹出外部窗口),可以切换到pyqtgraph的jupyter widget后端:

# %%
import pyqtgraph as pg
import numpy as np

# 设置使用jupyter widget后端
pg.setConfigOption('useWidget', True)

x = np.linspace(0,10)
y = np.linspace(0,10)
X, Y = np.meshgrid(x, y)
img = np.sin(X)*np.sin(Y)

# 创建图像widget并显示
view = pg.ImageView()
view.setImage(img)
view

图像会直接渲染在单元格下方,无需额外弹出窗口。

方案3:使用matplotlib兼容模式(备选)

如果更熟悉matplotlib的使用逻辑,也可以借助matplotlib完成图像渲染,避免Qt事件循环冲突:

# %%
import pyqtgraph as pg
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0,10)
y = np.linspace(0,10)
X, Y = np.meshgrid(x, y)
img = np.sin(X)*np.sin(Y)

# 转换为matplotlib格式显示
plt.imshow(img, cmap='viridis')
plt.colorbar()
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 03:42:08