Python:pyQt、QThread 和 matplotlib:第二次调用子图崩溃
我正在尝试用matplotlib绘制图表,数据来自一个线程。首先,我通过一个pyqt按钮启动这个线程,一切都很顺利。但是,当我第二次按下按钮时,子图就崩溃了,因为我想是元组不能被修改。这是我简化后的代码,你可以试试看:
from PyQt4 import QtGui, QtCore import matplotlib.pyplot as plt import numpy as np from PyQt4.Qt import * import sys class thread(QThread): def __init__(self, parent=None): QThread.__init__(self, parent) def __del__(self): self.wait() def render(self): self.start() def run(self): data = [(1, 10), (3, 100), (4, 1000), (5, 100000)] data_in_array = np.array(data) transposed = data_in_array.T x, y = transposed fig, ax = plt.subplots(1,1) ax.plot(x, y, 'ro') ax.plot(x, y, 'b-') plt.show() class Window(QtGui.QWidget): def __init__(self): QtGui.QWidget.__init__(self) self.button = QtGui.QPushButton('Test', self) self.button.clicked.connect(self.handleButton) layout = QtGui.QVBoxLayout(self) layout.addWidget(self.button) self.thread=thread() def handleButton(self): self.thread.render() if __name__ == '__main__': app = QtGui.QApplication(sys.argv) window = Window() window.show() sys.exit(app.exec_())
请问,我该如何解决这个问题,以避免崩溃,并且能多次使用我的按钮呢?谢谢!
2 个回答
0
我也遇到过同样的问题,一直在找解决办法。
加上这三行代码就解决了这个问题。请在导入pyplot之前添加这三行代码。
import matplotlib as mpl
mpl.rcParams['backend'] = "qt4agg"
mpl.rcParams['backend.qt4'] = "PySide"
0
这样混合你的Qt应用和Matplotlib(Matplotlib在后台使用Qt)并不是正确的方法。
想要更好的解释,可以查看这个链接:https://matplotlib.org/gallery/user_interfaces/embedding_in_qt_sgskip.html,比我说的要清楚多了。