python - 使用 Matplotlib 和 PyQt 进行动态绘图 - 卡住窗口

标签 python qt matplotlib pyqt pyqt4

目标:

我想在 pyQt4 GUI 窗口中嵌入 Matplotlib 图。剧情要及时更新。

问题:

窗口将卡住,直到绘图完成。我希望剧情能够实时更新。

上下文:

我们有正在处理某些数据的数值算法,我希望该图能够显示数据集如何受到算法的影响。该算法每约 0.5 秒完成一次迭代 - 每次迭代都必须更新绘图。

测试代码:

该算法被 test() 取代,它绘制随机点 100 次。下面的代码说明了问题:

import sys
from PlotGUI import *
import threading
from random import randint
import time

class GUIForm(QtGui.QDialog):

    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self,parent)
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)
        QtCore.QObject.connect(self.ui.pushButton, QtCore.SIGNAL('clicked()'), self.startSim)
        self.cPlot = None # custom plotter
        self.instantiatePlot()        

    def instantiatePlot(self):
        self.cPlot = CustomPlotter(self.ui.widget.canvas) 
        self.cPlot.prepareFigure()

    def startSim(self):
        self.cPlot.clear();        
        draw_thread = threading.Thread(target=self.cPlot.test())
        draw_thread.start()

class CustomPlotter():
    def __init__(self, canvas):
        print 'constructor'
        self.canvas = canvas        

    def prepareFigure(self):
        ax = self.canvas.ax

        ax.set_ylim([-1,101])
        #ax.set_xlim([dt[0],dt[1]])
        ax.set_ylim([-1, 10])
        self.canvas.draw()

    def clear(self):
        self.canvas.ax.clear()

    def test(self):
        canvas = self.canvas 
        ax = canvas.ax
        for x in range(0,100):
            y = randint(0,9)
            ax.plot(x, y, 'ro')
            print x
            canvas.draw()
            time.sleep(1)
            #canvas.show()
            #canvas.update()

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    myapp = GUIForm()
    myapp.show()
    sys.exit(app.exec_())

提前致谢。这是为了一些原型(prototype)设计,所以我愿意接受所有提供快速解决方案的选项/替代方案。

最佳答案

尝试实例化新线程时出现错误:

draw_thread = threading.Thread(target=self.cPlot.test())

这将立即在当前线程中执行测试方法,然后将结果(None)作为目标传递。您可能想做的是:

draw_thread = threading.Thread(target=self.cPlot.test)

Thread(target=None) 只是创建一个不执行任何操作的线程,只是立即退出,因此是有效的,不会产生任何表明此问题的异常。

由于 test() 方法是在 GUI 线程内启动的,因此 GUI 会被阻塞,直到该方法返回。

关于python - 使用 Matplotlib 和 PyQt 进行动态绘图 - 卡住窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33806598/

相关文章:

python - 如何在 AWS Elastic Beanstalk 上强制应用程序版本

java - 在 Java 中使用 Qt?

Qt 5.11 : Touch input inverted in my application

c++ - Qt drawRect 在后台

python - 在 python (matplotlib) 中优雅地停止(而不是暂停)动画情节

在 Matplotlib 中使用多边形进行 Numpy 数组切片

python - 按层次顺序打印树的内容,使用eval函数读取python中的输入树

python - Pygame Sprite 触摸

python - 如何从 matplotlib 中删除灰色边框

python - 使用 matplotlib 重复 x 轴值