Search code examples
pythonpython-3.xmatplotlibmatplotlib-widget

Make matplotlib button widget actuate when pressed, not when released


I made a simple interactive matplotlib figure that uses buttons to browse plots. A minimal example of one such button is:

import matplotlib.pyplot as plt
from matplotlib.widgets import Button

def message(_):
    print('Hello, World!')

buttonAxes = plt.axes([0.48, 0.48, 0.08, 0.08])
button = Button(buttonAxes, 'Button', color='#FFFFFF', hovercolor='#808080')
button.on_clicked(message)
plt.show()

This button behaves as intended, but actuates when the mouse button is released, and not when it is pressed. If I click on the button and don't release the mouse button, message is never called and nothing is printed to output. This makes buttons very jarring to use in cases like mine.

How do I make buttons like these actuate when pressed? Alternatively, how do I build a replacement button that does?

Python 3.8.1 on Windows 10.


Solution

  • You have to use the "button_press_event" event through the connect_event() method:

    button.connect_event("button_press_event", message)