Python 如何在matplotlib中将超时设置为pyplot.show()?
我正在使用python的Python 如何在matplotlib中将超时设置为pyplot.show()?,python,matplotlib,Python,Matplotlib,我正在使用python的matplotlib绘制图形 我想画一个有超时的图形,比如说3秒,然后窗口会关闭以继续代码 import matplotlib.pyplot as plt def close_event(): plt.close() #timer calls this function after 3 seconds and closes the window fig = plt.figure() timer = fig.canvas.new_timer(interval
matplotlib
绘制图形
我想画一个有超时的图形,比如说3秒,然后窗口会关闭以继续代码
import matplotlib.pyplot as plt
def close_event():
plt.close() #timer calls this function after 3 seconds and closes the window
fig = plt.figure()
timer = fig.canvas.new_timer(interval = 3000) #creating a timer object and setting an interval of 3000 milliseconds
timer.add_callback(close_event)
plt.plot([1,2,3,4])
plt.ylabel('some numbers')
timer.start()
plt.show()
print "Am doing something else"
我知道pyplot.show()
将创建一个具有无限超时的阻塞窗口pyplot.show(block=False)
或pyplot.draw()
将使窗口无阻塞。但是我想要的是让代码阻塞几秒钟
我有一个想法,我可能会使用事件处理程序或其他东西,但仍然不清楚如何解决这个问题。有什么简单而优雅的解决方案吗
假设我的代码如下所示:
Draw.py:
import matplotlib.pyplot as plt
#Draw something
plt.show() #Block or not?
下面是一个简单的示例,我创建了一个计时器来设置超时,并在计时器的回调函数中关闭了窗口
plot.close()
。在plot.show()
之前和三秒之后启动计时器,计时器调用close\u event()
,然后继续执行其余代码
import matplotlib.pyplot as plt
def close_event():
plt.close() #timer calls this function after 3 seconds and closes the window
fig = plt.figure()
timer = fig.canvas.new_timer(interval = 3000) #creating a timer object and setting an interval of 3000 milliseconds
timer.add_callback(close_event)
plt.plot([1,2,3,4])
plt.ylabel('some numbers')
timer.start()
plt.show()
print "Am doing something else"
希望这会有帮助。这对我在Mac OSX上不起作用 看起来有两个问题:
plt.close()
不足以退出
程序sys.exit()
工作\uuuu call\uuuu()
是处理此类问题的好方法
一个有状态的呼叫器from __future__ import print_function
import sys
import matplotlib.pyplot as plt
class CloseEvent(object):
def __init__(self):
self.first = True
def __call__(self):
if self.first:
self.first = False
return
sys.exit(0)
fig = plt.figure()
timer = fig.canvas.new_timer(interval=3000)
timer.add_callback(CloseEvent())
plt.plot([1,2,3,4])
plt.ylabel('some numbers')
timer.start()
plt.show()
print("Am doing something else")
睡眠
不起作用吗?嗯,我不知道把睡眠放在哪里。。。你的意思是我应该在show()之前或之后放置sleep?很抱歉几分钟前进行了多次修改。。。我还不熟悉StackOverflow的界面。。。。现在我已经完成了修改。我明白你的问题了。我不知道/