9

I have a matplotlib and I have created a button_press_event like this:

self.fig.canvas.mpl_connect('button_press_event', self.onClick)

def onClick(self, event)
    if event.button == 1:
        # draw some artists on left click

    elif event.button == 2:
        # draw a vertical line on the mouse x location on wheel click

    elif event.button == 3:
        # clear artists on right click

Now is it possible to modify the wheel click handler to something like this

    elif event.button == 2 or (event.button == 1 and event.key == "shift"):
        # draw a vertical line on the mouse x location 
        # on wheel click or on shift+left click 
        # (alternative way if there is no wheel for example)

It seems that button_press_event doesn't support keys and key_press_event doesn't support mouse button clicks, but I'm not sure.

Is there a way?

NotNone
  • 661
  • 1
  • 8
  • 13

2 Answers2

15

You can also bind a key press and key release events and do something like:

self.fig.canvas.mpl_connect('key_press_event', self.on_key_press)
self.fig.canvas.mpl_connect('key_release_event', self.on_key_release)

...

def on_key_press(self, event):
   if event.key == 'shift':
       self.shift_is_held = True

def on_key_release(self, event):
   if event.key == 'shift':
       self.shift_is_held = False

Then you can check in your onClick function if self.shift_is_held.

if event.button == 3:
    if self.shift_is_held:
        do_something()
    else:
        do_something_else()
Viktor Kerkez
  • 45,070
  • 12
  • 104
  • 85
  • Seems like a good idea and workaround until a proper support for modifier keys with mouse buttons is implemented. Thanks Viktor! – NotNone Aug 13 '13 at 07:30
  • FYI, you could use `event.key == 'shift+left'` to capture `shift` + `left` keyboard buttons – Nir Jun 23 '22 at 08:04
  • I like this answer, but I think it has issues when multiple keys are pressed, since `key_release_event` doesn't say _which_ key is released. E.g., consider: 1. press shift (`key_press_event`, `key='shift'`) 2. press ctrl (`key_press_event`, `key='ctrl+shift'`) 3. release shift (`key_release_event`, `key='ctrl+shift'`) 4. release ctrl (`key_release_event`, `key='ctrl'`) At the end, no keys are held but `shift_is_held==True`. You might change the conditionals to `if 'shift' in event.key`, but then if you release ctrl first shift is still held and yet `shift_is_held==False`... Any ideas? – Emma Sep 16 '22 at 21:33
2

If you are on Qt then you can simply use:

def onClick(self, event)
    # queries the pressed modifier keys
    mods = QGuiApplication.queryKeyboardModifiers()
    if event.button == 1 and mods == Qt.ShiftModifier:
        # do something when shift-clicking
architectonic
  • 2,871
  • 2
  • 21
  • 35