目标:
我想在 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/