plt.show()
不會返回,直到用戶關閉小部件/窗口。我很多情況下這種行爲是好的。爲什麼劇本應該在用戶花時間觀看精彩的圖形時進行呢? :-)但是,如果您要求您的程序繼續,請使用threading
模塊。在一個新線程中調用plt.show()
,並在讓主線程終止之前調用join()
這個線程。
編輯:
看起來事情並不那麼簡單。我創建了以下test.py
:
import threading
from matplotlib import pyplot as p
import time
p.plot([_ for _ in xrange(5)])
t = threading.Thread(target=p.show)
t.start()
for i in xrange(5):
print "lala %s" % i
time.sleep(1)
print "Waiting for plot thread to finish..."
t.join()
print "Finished."
測試它會導致這個錯誤:
14:43:42 $ python test.py
lala 0
lala 1
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python2.6/threading.py", line 532, in __bootstrap_inner
self.run()
File "/usr/lib/python2.6/threading.py", line 484, in run
self.__target(*self.__args, **self.__kwargs)
File "/usr/lib/pymodules/python2.6/matplotlib/backends/backend_tkagg.py", line 73, in show
manager.show()
File "/usr/lib/pymodules/python2.6/matplotlib/backends/backend_tkagg.py", line 385, in show
if not self._shown: self.canvas._tkcanvas.bind("<Destroy>", destroy)
File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 988, in bind
return self._bind(('bind', self._w), sequence, func, add)
File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 938, in _bind
needcleanup)
File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 1101, in _register
self.tk.createcommand(name, f)
RuntimeError: main thread is not in main loop
我從這個是p.show()
需要從主線程調用推斷。也許你必須這樣做:在另一個線程中獲取用戶輸入。
[...](http://stackoverflow.com/questions/12358312/keep-plotting-window-open-in-matplotlib) –