我使用 这个方便的类 在同一个 matplotlib 窗口中绘制多个选项卡式图。
它的工作效果非常惊人,但在创建第二个窗口后,Python 崩溃并出现错误
QGuiApplication::font(): no QGuiApplication instance and no application font set
。最小工作示例:
from plotWindow import plotWindow
import matplotlib.pyplot as plt
import numpy as np
for n in range(3):
pw = plotWindow()
x = np.arange(0, 10, 0.001)
for i in range(1,3):
f = plt.figure()
ysin = np.sin(i*x)
plt.plot(x, ysin, '--')
pw.addPlot(str(i), f)
pw.show()
我对PyQt5知之甚少,所以我真的不知道该去哪里寻找。谢谢你的帮助!
P.S.:为了完整起见:这里是该类的完整代码:
import matplotlib
matplotlib.use('qt5agg')
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
import matplotlib.pyplot as plt
import numpy as np
from PyQt5.QtWidgets import QMainWindow, QApplication, QPushButton, QWidget, QAction, QTabWidget,QVBoxLayout
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot
import sys
class plotWindow():
def __init__(self, parent=None):
self.app = QApplication(sys.argv)
self.MainWindow = QMainWindow()
self.MainWindow.__init__()
self.MainWindow.setWindowTitle("plot window")
self.canvases = []
self.figure_handles = []
self.toolbar_handles = []
self.tab_handles = []
self.current_window = -1
self.tabs = QTabWidget()
self.MainWindow.setCentralWidget(self.tabs)
self.MainWindow.resize(1280, 900)
self.MainWindow.show()
def addPlot(self, title, figure):
new_tab = QWidget()
layout = QVBoxLayout()
new_tab.setLayout(layout)
figure.subplots_adjust(left=0.05, right=0.99, bottom=0.05, top=0.91, wspace=0.2, hspace=0.2)
new_canvas = FigureCanvas(figure)
new_toolbar = NavigationToolbar(new_canvas, new_tab)
layout.addWidget(new_canvas)
layout.addWidget(new_toolbar)
self.tabs.addTab(new_tab, title)
self.toolbar_handles.append(new_toolbar)
self.canvases.append(new_canvas)
self.figure_handles.append(figure)
self.tab_handles.append(new_tab)
def show(self):
self.app.exec_()
此问题已报告(但未答复)此处。
通过稍微编辑类的启动来修复它(请参阅完整的片段那里,以及详细的更改那里):
def __init__(self, parent=None):
self.app = QApplication.instance()
if not self.app:
self.app = QApplication(sys.argv)
self.MainWindow = QMainWindow()
self.MainWindow.setWindowTitle("plot window")
self.canvases = []
self.figure_handles = []
self.toolbar_handles = []
self.tab_handles = []
self.current_window = -1
self.tabs = QTabWidget()
self.MainWindow.setCentralWidget(self.tabs)
self.MainWindow.resize(1280, 900)
self.MainWindow.show()