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

标签 python matplotlib

我正在使用 python 的 matplotlib 来绘制图形。

我想画一个带有超时的图形,比如 3 秒,然后窗口将关闭以在代码上移动。

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

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

假设我的代码如下:

绘图.py:

import matplotlib.pyplot as plt

#Draw something
plt.show() #Block or not?

最佳答案

这是一个简单的示例,其中我创建了一个计时器来设置您的超时并在计时器的回调函数中关闭窗口 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("I am doing something else")

希望对您有所帮助。

关于python - 如何在 matplotlib 中为 pyplot.show() 设置超时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30364770/

相关文章:

python - DoesNotExist 在/admin/login/站点匹配查询不存在

Python 3d 绘图设置固定色阶

matplotlib - 在 matplotlib 子图中绘制多个图像文件

python - 如何保存n-d numpy数组数据,下次快速读取?

python - 如果不属于 Python 中的一组匹配模式,则删除字符串中的字符

python - 通过串行数据使用 Python mplotlib 动画化 3D 散点图

python - 如何创建按月分组的年度条形图

python - 将 3D 图的轴放置在图表内

python - 将图例扩展到 2 个子图

python - 如果将 DataFrame 保存到磁盘,如果您在脚本中使用该 DataFrame,Spark 是否会加载该数据?