[Python] Connecting CTRL + Right Click to matplotlib FigureCanvasTkAgg

Discussão em 'Python' iniciado por Stack, Maio 28, 2025.

  1. Stack

    Stack Membro Participativo

    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()

    Continue reading...

Compartilhe esta Página