Skip to main content
 首页 » 编程设计

python之如何将 BytesIO 与 matplotlib 和 pyqt5 一起使用

2024年10月01日6grandyang

我在 matplotlib 中制作了一个图形,并想将其制作成图像并在我的 pyqt5 应用程序中使用它。有人建议我为此使用 BytesIO。到目前为止,这是我的代码:

绘制图表:

... 
plt.axis('equal') 
buff = io.BytesIO() 
plt.savefig(buff, format="png") 
print(buff) 
return buff 

然后在另一个脚本中调用:

def minionRatioGraphSetup(self, recentMinionRatioAvg): 
    image = minionRatioGraph(recentMinionRatioAvg) 
    label = QtWidgets.QLabel() 
    pixmap = QtGui.QPixmap(image) 
    label.setPixmap(pixmap) 
    label.setGeometry(QtCore.QRect(0,0,200,200)) 

它在 pixmap = QtGui.QPixmap(image) 停止工作,我不确定为什么。另外:我怎么能把它放在我的主窗口中?因为我怀疑那里的代码会起作用 哈哈

请您参考如下方法:

我确信有一个使用缓冲区的解决方案。但是,要使字节格式正确似乎相当复杂。因此,另一种方法是将图像保存到磁盘,然后从那里加载它。

import sys 
from PyQt4 import QtGui 
import matplotlib.pyplot as plt 
import numpy as np 
 
def minionRatioGraph(): 
    plt.plot([1,3,2]) 
    plt.savefig(__file__+".png", format="png") 
 
 
class App(QtGui.QWidget): 
 
    def __init__(self): 
        super(App, self).__init__() 
        self.setGeometry(300, 300, 250, 150) 
        self.setLayout(QtGui.QVBoxLayout()) 
        label = QtGui.QLabel() 
        label2 = QtGui.QLabel("Some other text label")  
 
        minionRatioGraph() 
 
        qimg = QtGui.QImage(__file__+".png")   
        pixmap = QtGui.QPixmap(qimg) 
 
        label.setPixmap(pixmap) 
        self.layout().addWidget(label) 
        self.layout().addWidget(label2) 
        self.show() 
 
 
if __name__ == '__main__': 
    app = QtGui.QApplication([]) 
    ex = App() 
    sys.exit(app.exec_())