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()
需要从主线程调用。也许您必须反过来做:在另一个线程中获取您的用户输入。