"event loop is already running" 在应用程序中使用 pdb 调试器时 运行 matplotlib 和 PySide2

"event loop is already running" while using the pdb debugger in an application running with matplotlib and PySide2

我有一个应用程序,用户必须在其中使用 matplotlib 单击图像。我想使用调试器 pdb(第 53 行),但是,当我启动应用程序并单击按钮时,一条消息

QCoreApplication::exec: The event loop is already running

出现并阻止我使用调试器。我怀疑它来自以下几行,但我不确定

import matplotlib
try:
    matplotlib.rcParams['backend.qt5'] = 'PySide2'
except (KeyError, Exception):
    pass
matplotlib.use('Qt5Agg')

我确实实现了这些行,这要归功于我从我之前问过的这个问题中得到的答案:

如何保留与后端相同的代码结构并能够使用 pdb 调试器?

import sys
import os 
import subprocess
from subprocess import call
import matplotlib
import pdb

try:
    matplotlib.rcParams['backend.qt5'] = 'PySide2'
except (KeyError, Exception):
    pass
matplotlib.use('Qt5Agg')
import matplotlib.pyplot as plt


from PySide2 import QtGui
from PySide2 import QtCore
from PySide2.QtWidgets import QWidget, QApplication, QPushButton, QFileDialog
from PySide2.QtCore import QFile, QTextStream

os.environ['QT_MAC_WANTS_LAYER'] = '1'


from IPython.core import ultratb
import pdb

sys.excepthook = ultratb.FormattedTB(mode='Verbose', color_scheme='Linux', call_pdb=True)


class GUI(QWidget):
    def __init__(self):
        super(GUI, self).__init__()

        self.initUI()

    def initUI(self):

        height_btn = 40 
        width_btn = 350
        
        button_position_x = 0
        button_position_y = 20 

        button_position_x = button_position_x = 0
        button_position_y = button_position_y + 400
        btn15 = QPushButton('button', self)     
        btn15.clicked.connect(self.Plotfunction)
        btn15.resize(width_btn, height_btn)
        btn15.move(button_position_y, button_position_x)       
        self.show()

    def Plotfunction(self):
        pdb.set_trace()
        print("ok")


def main():

    app = QApplication(sys.argv)
    ex = GUI()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

默认情况下,matplotlib 将加载已经导入的绑定(PyQt 或 PySide2),或者如果加载了 none,那么它将尝试导入它们,第一个成功导入的将使用它。显然,在 OP 的情况下,它首先导入 PyQt 导致该问题。解决方案是导入 PySide2,然后导入 matplotlib,以便它更喜欢 PySide2 作为后端绑定。