我可以将点击事件绑定到绘图(即打印被点击的坐标),如下所示:
from matplotlib.backend_bases import MouseButton
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [2, 3, 1, 4]
fig, ax = plt.subplots()
ax.plot(x, y)
def plotClick(event):
if event.button == MouseButton.LEFT:
print('Clicked at x=%f, y=%f' %(event.xdata, event.ydata))
plt.connect('button_press_event', plotClick)
plt.show()
我想做同样的事情,是包含在一个画布内的绘图窗口,像这样:
from matplotlib.backend_bases import MouseButton
import tkinter as tk
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
window = tk.Tk()
fig = Figure(figsize=(5, 3))
ax = fig.add_subplot(111)
x = [1, 2, 3, 4]
y = [2, 3, 1, 4]
line, = ax.plot(x, y)
canvas = FigureCanvasTkAgg(fig)
canvas.draw()
canvas.get_tk_widget().pack()
def plotClick(event):
if event.button == MouseButton.LEFT:
print('Clicked at x=%f, y=%f' %(event.xdata, event.ydata))
window.mainloop()
我需要做什么才能在这里实现相同的行为?
注意:我知道可以使用 将事件直接绑定到画布上canvas.get_tk_widget().bind('<Button-1>', plotClick)
def plotClick(event):
print('Clicked at x=%f, y=%f' %(event.x, event.y))
使用画布上的像素坐标,而不是绘图中的坐标。
不使用plt.connect
,使用
canvas.mpl_connect('button_press_event', plotClick)
你可以使用event.xdata
和event.ydata
访问图中的坐标,但你也可以使用event.x
和event.y
访问画布上的(像素)坐标。