2017-04-18 419 views
1

我在另一个绘制图形的脚本中有一个函数,所以图形已经预先绘制好,我只是想将它放到我的PyQt5界面上的一个小部件中。我输入了它,当它运行时,它会打开两个窗口,一个窗口在图形中,一个在用户界面中。任何想法?Matplotlib将图形嵌入到用户界面中PyQt5

下面是代码:

def minionRatioGraph(recentMinionRatioAvg): 
    x = recentMinionRatioAvg 
    a = x*10 
    b = 100-a 
    sizes = [a, b] 
    colors = ['#0047ab', 'lightcoral'] 
    plt.pie(sizes, colors=colors) 

    #determine score colour as scolour 
    if x < 5: 
     scolour = "#ff6961" #red 
    elif 5 <= x < 5.5: 
     scolour = "#ffb347" #orange 
    elif 5.5 <= x < 6.5: 
     scolour = "#77dd77" #light green 
    elif 6.5 <= x: 
     scolour = "#03c03c" # dark green 

    #draw a circle at the center of pie to make it look like a donut 
    centre_circle = plt.Circle((0,0),0.75, fc=scolour,linewidth=1.25) 
    fig = plt.gcf() 
    fig.gca().add_artist(centre_circle) 

    # Set aspect ratio to be equal so that pie is drawn as a circle. 
    plt.axis('equal') 
    plt.show() 

这是一个脚本。在我的GUI脚本,我已经导入这些:

from PyQt5 import QtCore, QtGui, QtWidgets 
import sqlite3 
import matplotlib.pyplot as plt 
from matplotlib.figure import Figure 
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as 
FigureCanvas 
from graphSetup import * 

而在我的窗口类的开始,设置功能之前,我有这样的功能:

def minionGraphSetup(self, recentMinionRatioAvg): 
    minionRatioGraph(recentMinionRatioAvg) 

回答

0

而不是调用plt.show的需要将导入的脚本生成的图放入PyQt GUI的FigureCanvas中。

在绘制脚本

所以做

def minionRatioGraph(recentMinionRatioAvg): 
    ... 
    fig = plt.gcf() 
    fig.gca().add_artist(centre_circle) 
    plt.axis('equal') 
    #plt.show() <- don't show window! 
    return fig 

在你的GUI脚本中使用获得的图形将其放置到画布上。

def minionGraphSetup(self, recentMinionRatioAvg): 
    fig = minionRatioGraph(recentMinionRatioAvg) 
    ... 
    self.canvas = FigureCanvas(fig, ...) 


如果你想返回一个图片,你可以将它保存到一个字节缓冲区,

import io 
def minionRatioGraph(recentMinionRatioAvg): 
    ... 
    fig = plt.gcf() 
    fig.gca().add_artist(centre_circle) 
    plt.axis('equal') 
    buff = io.BytesIO() 
    plt.savefig(buff, format="png") 
    return buff 

,然后显示它在PyQt的GUI图像。 (我没有测试下面,所以它可能有点不同。)

def minionGraphSetup(self, recentMinionRatioAvg): 
    image = minionRatioGraph(recentMinionRatioAvg) 
    label = QLabel() 
    pixmap = QPixmap(image) 
    label.setPixmap(pixmap) 
+0

虽然这个工程,这不是我所寻找的,而不是你的错,我的。你知道我怎么可能将图形直接导出为gui图像?我知道你可以将图形保存为图像,但是如何将更新后的图像放在屏幕上,据我所知,当编译资源文件时,所有图像保持不变,我不知道如何重新加载它。 –

+0

我更新了图像的答案。我目前无法进行测试,所以请将其作为路线图作为工作代码。 – ImportanceOfBeingErnest

+0

代码停止在'pixmap = QPixmap(image)'工作,我不确定为什么?有什么想法吗?另外,我将如何将它放入我的窗户?我会传递窗口的名称并将self.centralwidget放入QLabel括号中吗?谢谢 –