如何在matplotlib中将超时设置为pyplot.show()?

Tin*_*hih 7 python matplotlib

我正在使用python matplotlib来绘制数字.

我想绘制一个超时的数字,比如3秒,窗口将关闭以移动代码.

我知道pyplot.show()会创建一个无限超时的阻塞窗口; pyplot.show(block=False)或者pyplot.draw()会使窗口无阻塞.但我想要的是让代码阻塞几秒钟.

我提出了一个想法,我可能会使用事件处理程序或其他东西,但仍然不清楚如何解决这个问题.有没有简单而优雅的解决方案?

假设我的代码如下:

Draw.py:

import matplotlib.pyplot as plt

#Draw something
plt.show() #Block or not?
Run Code Online (Sandbox Code Playgroud)

Dee*_*epa 18

这是一个简单的例子,我创建了一个计时器来设置你的超时并plot.close()在计时器的回调函数中执行窗口关闭.plot.show()在三秒计时器调用之前和之后启动计时器close_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"
Run Code Online (Sandbox Code Playgroud)

希望这很有帮助.