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

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

我正在使用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 = 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的界面。。。。现在我已经完成了修改。我明白你的问题了。我不知道/