2

I am trying to active a mode when a key is pressed and turn it off when the key is released. So, while holding a key, be in this mode. The problem is, matplotlib is interpreting a held key as many key presses and releases in rapid succession. Anyone know how to stop this?

here is some sample code:

import matplotlib.pyplot as plt
import numpy as np

def key_press(event):
     # toggle mode on when key pressed
    print(f'{event.key} pressed')

def key_release(event):
     # toggle mode off when key released
    print(f'{event.key} released')


fig = plt.figure(figsize=(8,6))
ax1 = fig.add_subplot(111)

x=np.random.random([20])
y=np.random.random([20])
ax1.scatter(x,y)

fig.canvas.mpl_connect('key_press_event',key_press)
fig.canvas.mpl_connect('key_release_event',key_release)

plt.show()
Kyle Roth
  • 29
  • 3
  • It looks like Qt (the plot backend) has an [isAutoRepeat flag](https://stackoverflow.com/questions/10046945/qkeypress-event-in-pyqt), but Matplotlib doesn't expose it. You may be able to monkey-patch Matplotlib to keep track of the autorepeat. – Han-Kwang Nienhuys Jun 08 '20 at 22:17
  • What are you trying to do when you are activating the alternative mode? If you want ultimately want to modify mouse actions, then there are other ways to achieve that, for example: https://stackoverflow.com/a/18145817/2912349. – Paul Brodersen Jun 09 '20 at 10:39

1 Answers1

0

I was/am experiencing the same problem. I believe Matplotlib is working correctly (at least for me on Pop OS/Linux); there is an accessibility setting called repeat keys or auto repeat keys. When enabled, this setting will release your key if you press on it for X amount of time and repress it again and then the process of pressing and releasing speeds up. Matplotlib will get these inputs as key_press_event and key_release_event. Indeed when I disable this setting in the system settings, holding down a key will only send key_press_event once.

Not sure what the fix would be (without disabling the setting), perhaps some hack with keyboard library but I am not sure if this library experiences the same problem as Matplotlib.

lutrarutra
  • 180
  • 1
  • 10