1

可能重复:
如何让情节不消失?

我正在编写一个用于分析一些数据的命令行界面 python 程序。它问用户一堆问题,并在脚本中的几个点显示 matplotlib pyplot plot neds,但我想显示它并继续使用脚本,如下所示:

import matplotlib.pyplot as plt
import numpy as np

plt.figure()
plt.plot(np.arange(10),np.arange(10)**2)

plt.show()
print 'continuing the program'

我曾尝试plt.draw()与子图一起使用,但它似乎在脚本中不起作用。

编辑:除了绘图窗口没有响应之外,我使用plt.ion()了哪种作品,并且未显示放大工具等按钮

4

1 回答 1

2

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

于 2012-09-11T12:36:07.833 回答