1

I'm trying to bind CTRL + Right click to a matplotlib FigureCanvasTkAgg. So far, I used mpl_connect to change the state of a ctrl variable when the key is pressed and then checked if it was True when the user clicks on the figure. I was wondering if there was a way to do the same thing without having to use this "workaround". The list of event connections doesn't appear to handle compound events.

import tkinter as tk
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

ctrl = False

def ctrlpressed(event):
    global ctrl
    if event.key == 'control':
        ctrl = True

def ctrlreleased(event):
    global ctrl
    if event.key == 'control':
        ctrl = False

def scrolled(event):
    if ctrl and event.button == 3:
        print(f'({event.xdata}, {event.ydata})')

root = tk.Tk()
root.geometry("600x800")

fig, ax = plt.subplots(facecolor="w")
ax.plot([1, 2], [1, 2], '-o')

canvas = FigureCanvasTkAgg(fig, master=root)
canvas.draw()
canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True)

canvas.mpl_connect('key_press_event', ctrlpressed)
canvas.mpl_connect('key_release_event', ctrlreleased)
canvas.mpl_connect('button_press_event', scrolled)

root.mainloop()
2
  • 2
    Did you try checking event.key inside scrolled()? Commented May 28 at 13:53
  • Ah that's so simple and it works. Thanks, can you write an answer so I can accept it ? Commented May 28 at 14:11

1 Answer 1

4

According to the linked document on event handling, you can check the event.key to see whether Control key is pressed or not inside the mouse event handler scrolled():

def scrolled(event):
    if event.key == 'control' and event.button == 3:
        print(f'({event.xdata}, {event.ydata})')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.