当 运行 来自 Anaconda (Spyder) 时如何可靠地说服 matplotlib 使用 PySide2 后端

How to reliably convince matplotlib to use PySide2 backend when running from Anaconda (Spyder)

我正在创建一个使用 matplotlib 的 PySide2 应用程序。我在安装了 PySide2 的环境中从 Spyder 运行 宁这个应用程序。这导致应用程序从 iPython 控制台变为 运行。沿线的某个地方,导入了 PyQt5,我试图清除它以说服 matplotlib 我真的想使用 PySide2,而不是 PyQt5。像下面这样的东西直到最近才起作用,我不太确定它为什么停止了,但可以肯定地说这种方法是不可靠的。我怎样才能绝对说服 matplotlib 我想要 PySide2?

我试过在操作系统中设置环境变量QT_API(Windows10),但是这种情况下Spyder本身就是拒绝打开

import sys
import os

ps = list(filter(lambda x: 'PyQt5' in x, sys.modules))
for p in ps:
    print(f"purging module {p}")
    sys.modules.pop(p)
    
# matplotlib.__init__ uses this
os.environ["MPLBACKEND"] = "PySide2"

# matplotlib.backends.qt_compat uses this
os.environ["QT_API"] = "PySide2"

import PySide2.QtCore

assert "PyQt5.QtCore" not in sys.modules
assert "PySide2.QtCore" in sys.modules

# rcParams has the right idea
from matplotlib import rcParams
print(rcParams["backend"])

# qt_compat has the WRONG idea!
import matplotlib.backends.qt_compat as qt_compat
print(qt_compat.QT_API)

# The FigureCanvasWidget is of the wrong (PyQt5) type
from matplotlib.backends.backend_qt5agg import FigureCanvas
import inspect
print(inspect.getmro(FigureCanvas))

回答这个问题,它停止工作的原因是因为我在Spyder设置下的ipython选项卡中为Matplotlib图形设置了'activate support'。取消选中后,上面的工作。