'Tkinter and matplotlib: Bind to FigureCanvasTkAgg to extract curser position in figure?
I want to plot a 2d array using matplotlib, and then extract the curser position when I click on the plotted image. Here's a minimal working example of how I would write it:
from tkinter import *
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib import pyplot as plt
def callback(event):
print ("clicked at", event.x, event.y)
root = Tk()
mf = Frame()
figure = plt.Figure()
axes = figure.add_subplot(111)
canvas_wid = FigureCanvasTkAgg(figure, master=mf)
canvas_wid.get_tk_widget().pack()
root.bind("<Button-1>", callback)
mf.pack()
root.mainloop()
However, I don't want to have the coordinates regarding root, but within the figure. When I bind the click to mf, the program runs, but clicking doesn't trigger any responde. When I bind it to the Canvas widget - which,to my understanding, would be exactly what I want, I get the following error message:
AttributeError: 'FigureCanvasTkAgg' object has no attribute 'bind'
Apparently, Canvas is not a widget when I define it using FigureCanvasTKagg? What structure is needed to extract the cursor position within a figure?
I am fairly new to GUI programming in python and I assume that I am missing a very basic point. I checked the reference manual for tkinter and matpotlib, read plenty of other question, but was not able to find my fallacy.
Solution 1:[1]
You want to use mpl_connect
. Take a look at https://www.pythonfixing.com/2022/05/fixed-bind-event-to-click-on-plot-in.html.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Ed Behn |