.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "gallery/event_handling/keypress_demo.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. meta:: :keywords: codex .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code .. rst-class:: sphx-glr-example-title .. _sphx_glr_gallery_event_handling_keypress_demo.py: ============== Keypress event ============== Show how to connect to keypress events. .. note:: This example exercises the interactive capabilities of Matplotlib, and this will not appear in the static documentation. Please run this code on your machine to see the interactivity. You can copy and paste individual parts, or download the entire example using the link at the bottom of the page. .. GENERATED FROM PYTHON SOURCE LINES 16-42 .. image-sg:: /gallery/event_handling/images/sphx_glr_keypress_demo_001.png :alt: Press a key :srcset: /gallery/event_handling/images/sphx_glr_keypress_demo_001.png, /gallery/event_handling/images/sphx_glr_keypress_demo_001_2_00x.png 2.00x :class: sphx-glr-single-img .. code-block:: Python import sys import matplotlib.pyplot as plt import numpy as np def on_press(event): print('press', event.key) sys.stdout.flush() if event.key == 'x': visible = xl.get_visible() xl.set_visible(not visible) fig.canvas.draw() # Fixing random state for reproducibility np.random.seed(19680801) fig, ax = plt.subplots() fig.canvas.mpl_connect('key_press_event', on_press) ax.plot(np.random.rand(12), np.random.rand(12), 'go') xl = ax.set_xlabel('easy come, easy go') ax.set_title('Press a key') plt.show() .. _sphx_glr_download_gallery_event_handling_keypress_demo.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: keypress_demo.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: keypress_demo.py ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_