gpt4 book ai didi

python - 为什么 matplotlib 只需要在主线程中绘制?

转载 作者:太空宇宙 更新时间:2023-11-03 15:07:02 29 4
gpt4 key购买 nike

我正在尝试实时绘制发电机的输出。

以下代码按预期工作(Ctrl-C 终止执行):

import numpy as np
import pylab as p
from Queue import Queue
from threading import Thread
import time

def dataGenerator():
while True:
yield np.random.random()

def populate():
f = dataGenerator()
while True:
x = f.next(); y = f.next()
q.put([x,y])

q = Queue()

p.figure(); p.hold(True); p.show(block=False)

populatorThread = Thread(target=populate)
populatorThread.daemon = True
populatorThread.start()

while True:
data = q.get()
x = data[0]
y = data[1]
p.plot(x,y,'o')
p.draw()
q.task_done()

populatorThread.join()

但是,如果我将绘图放在一个线程中,我会得到 RuntimeError: main thread is not in main loop:

import numpy as np
import pylab as p
from Queue import Queue
from threading import Thread
import time

def dataGenerator():
while True:
yield np.random.random()

def plotter():
while True:
data = q.get()
x = data[0]
y = data[1]
p.plot(x,y,'o')
p.draw()
print x,y
q.task_done()

q = Queue()

p.figure(); p.hold(True); p.show(block=False)

plotThread = Thread(target=plotter)
plotThread.daemon = True
plotThread.start()

f = dataGenerator()
while True:
x = f.next()
y = f.next()
q.put([x,y])

plotThread.join()

为什么 matplotlib 关心哪个线程进行绘图?

编辑:我不是在问如何解决这个问题,而是问为什么首先会发生这种情况。

最佳答案

这可能是您用于后端的 GUI。 GUI 可能希望在主线程中找到自己,但当 matplotlib 调用 get_current_fig_manager().canvas.draw() 时却不是。

例如,当我这样做时,我得到以下回溯:

Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 810, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 763, in run
self.__target(*self.__args, **self.__kwargs)
File "tmp.py", line 18, in plotter
p.draw()
File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 555, in draw
get_current_fig_manager().canvas.draw()
File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_tkagg.py", line 349, in draw
tkagg.blit(self._tkphoto, self.renderer._renderer, colormode=2)
File "/usr/lib/pymodules/python2.7/matplotlib/backends/tkagg.py", line 13, in blit
tk.call("PyAggImagePhoto", photoimage, id(aggimage), colormode, id(bbox_array))
RuntimeError: main thread is not in main loop

注意 tk.call(...) 行。您得到的异常不是从 matplotlib 引发的,而是从 TkInter 引发的。

关于python - 为什么 matplotlib 只需要在主线程中绘制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31444972/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com