How to set timeout on pyplot.show () in matplotlib?

I use python matplotlibto draw shapes.

I want to draw a figure with a timeout of, say, 3 seconds, and the window closes to move around the code.

I knew that I pyplot.show()would create a lock window with an unlimited timeout; pyplot.show(block=False)or pyplot.draw()make the window non-blocking. But I want a block of code a few seconds.

I got the idea that I can use an event handler or something like that, but still don't quite understand how to solve this. Is there a simple and elegant solution?

Suppose my code is as follows:

Draw.py:

import matplotlib.pyplot as plt

#Draw something
plt.show() #Block or not?
+4
source share
2 answers

, - 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"

, .

+10

Mac OSX.

, :

  • plt.close() sys.exit() .

  • , , . . . , - . __call__() .

:

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")
+3

Source: https://habr.com/ru/post/1589125/


All Articles