我已经创建了这个非常简单的代码,它会根据我单击或双击条形图上的一个条形来生成一条消息。
我不明白的是,为什么它的工作前两次和第三次,点击任何地方,它产生一个错误。
我在哪里点击并不重要,无论是左还是右等等。总是第三次。我很乐意理解为什么会发生这种情况。
我得到的错误是
canvas = property(lambda self: self.ref_artist.figure.canvas)
属性错误:“NoneType”对象没有属性“canvas”
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import tkinter as tk
import mplcursors
# create tkinter app window
root = tk.Tk()
root.title("Barplot with Cursor")
# create Figure object in matplotlib
fig, ax = plt.subplots()
# add data to the plot
data = [5, 10, 15, 20, 25]
ax.bar(range(len(data)), data)
# embed plot into tkinter app using FigureCanvasTkAgg
canvas = FigureCanvasTkAgg(fig, master=root)
canvas.draw()
canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
# class to keep track of latest event
class LatestEvent:
def __init__(self):
self.event = None
def update(self, event):
self.event = event
def get(self):
return self.event
latest_event = LatestEvent()
# function to handle selection event
def on_select(sel):
print(f"Selected region: ({sel.target[0]:.2f}, {sel.target[1]:.2f})")
# function to handle left-click event
def on_left_click(event):
if event.dblclick:
print('Left double')
else:
print('Left single')
# bind left-click events to on_left_click function
def left_click_handler(event):
latest_event.update(event)
root.after(300, on_left_click_wrapper)
def on_left_click_wrapper():
event = latest_event.get()
if event:
on_left_click(event)
latest_event.update(None)
canvas.mpl_connect("button_press_event", lambda event: left_click_handler(event) if event.button == 1 else None)
# function to handle right-click event
def on_right_click(event):
if event.button == 3:
if event.dblclick:
print("Right double-click message")
else:
print("Right single-click message")
# bind right-click events to on_right_click function
canvas.mpl_connect("button_press_event", lambda event: on_right_click(event) if event.button in (1,3) else None)
# bind left-click events to on_select function
c = mplcursors.cursor(ax, hover=False)
c.connect("add", lambda sel: on_select(sel))
# start tkinter mainloop
root.mainloop()
1条答案
按热度按时间oxalkeyp1#
这是Matplotlib的一个bug。详情请参见issue#25440。
现在,您可以像这样降级到3.7.0版本。