How can I use spacebar to close Matplotlib/Pyplot plots?

Viewed 162

In Close a matplotlib figure using keyboard I learned that you can add keybinds to various matplotlib commands, including key.quit which exits the plot.

The keybinds can be assigned via: plt.rcParams["keymap.quit"] = ['ctrl+w', 'cmd+w', 'q']

However, when I add space or spacebar to the list, space doesn't work. I know that list is defaults, so either I'm not modifying them at all or I have the name for spacebar wrong.

Does anyone know how to do this?

1 Answers

There is a paucity of documentation on exactly what the key mappings are for this functionality, but you can find out with this code snippet:

>>> from matplotlib import pyplot as plt
>>> fig = plt.figure()
>>> fig.canvas.mpl_connect('key_press_event', lambda evt: print(repr(evt.key)))
8

Then

>>> plt.show()

will open an empty plot window. Pressing keys in the window will print to your terminal the associated keymap code.

When pressing the space bar I get:

' '

Confirmed that setting plt.rcParams['keymap.quit'].append(' ') works--pressing the space bar closes the window.

Related