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

pytest调试控制台模式下matplotlib绘图出现废弃警告求助

pytest运行matplotlib绘图出现DeprecationWarning且图像无法显示的解决方法

这个问题本质是matplotlib的Qt后端与PySide6 6.5+的API变更冲突,同时pytest的运行环境未正确初始化GUI上下文,导致图像无法显示,并非单纯的pytest与matplotlib冲突。报错里提到的Qt::ApplicationAttribute.AA_EnableHighDpiScaling在PySide6 6.5及以上版本已被废弃,但matplotlib 3.7.1的Qt后端仍在调用该旧属性,加上pytest控制台模式下GUI初始化逻辑的差异,最终引发警告并导致图像无法弹出。

以下是具体解决建议:

1. 显式指定非Qt后端规避冲突

如果不需要Qt后端,可以直接让matplotlib使用其他后端(比如TkAgg),绕开PySide6的API问题:

# 在测试文件最开头添加
import matplotlib
matplotlib.use('TkAgg')

import numpy as np
import matplotlib.pyplot as plt

def test_sin():
    x = np.arange(0, 25, 0.1)
    y = np.sin(x)
    plt.plot(x, y)
    plt.show()

2. 使用pytest-qt插件正确初始化Qt上下文

pytest-qt是专门处理Qt GUI测试的插件,能帮你正确管理Qt应用生命周期,解决GUI初始化问题:

  • 先安装插件:pip install pytest-qt
  • 修改测试代码:
import matplotlib
matplotlib.use('QtAgg')  # 明确使用Qt后端
import numpy as np
import matplotlib.pyplot as plt

def test_sin(qtbot):
    x = np.arange(0, 25, 0.1)
    y = np.sin(x)
    plt.plot(x, y)
    
    # 将matplotlib的窗口注册到qtbot管理
    fig_window = plt.gcf().canvas.manager.window
    qtbot.addWidget(fig_window)
    
    # 非阻塞显示图像,如需自动关闭可添加等待
    plt.show(block=False)
    # qtbot.wait(3000)  # 可选:等待3秒后自动关闭窗口

3. 抑制废弃警告(仅消除警告提示)

如果只是不想看到警告,但不影响核心功能,可以添加警告过滤:

# 在测试文件开头添加
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning, message=r".*AA_EnableHighDpiScaling.*")

import numpy as np
import matplotlib.pyplot as plt

def test_sin():
    x = np.arange(0, 25, 0.1)
    y = np.sin(x)
    plt.plot(x, y)
    plt.show()

4. 调整库版本适配

matplotlib 3.7.1对PySide6 6.5的支持存在滞后,可尝试:

  • 降级PySide6到6.4.x版本:pip install pyside6==6.4.3
  • 升级matplotlib到最新稳定版:pip install --upgrade matplotlib

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 06:43:09