How to capture keyboard clicks

Next, we must capture the return value by inserting plt.gcf ( ) .canvas.mpl_disconnect (cid) to remove the event handler. Therefore, by adding this function, we can click to draw a circle.

However, subsequent clicks will not perform anything as the event handler has been removed:

As we can see, the mouse isn't the only thing that can capture events. We can also capture events for key presses. By using the canvas.mpl_connect command and passing the first argument as key_press _event (the first argument is a string describing which event to capture and the second argument is the callback function), we generate a new plot, as shown in the following code:

# Keyboard events with key_press_event
plt.clf()
plt.plot(np.random.normal(size=100))
def redraw(event):
if event.key == 'r':
plt.cla()
plt.plot(np.random.normal(size=100))
plt.gcf().canvas.draw()
# Add a listener for key presses.
cid = plt.gcf().canvas.mpl_connect('key_press_event', redraw)

From the preceding code we will get the following output:

From the preceding output, we can see that if the event.key that is inserted is the r key, it clears the previous image and draws a new, random Markov process.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset