我的 Tkinter GUI 中嵌入了一个图,我试图在图中添加一个显示鼠标位置的十字准线

I have a plot embedded in my Tkinter GUI, Im trying to add to the plot a crosshair that shows where the mouse is

在正常的情节中,十字准线工作得很好 see screenshot here

但是当我的绘图嵌入到 GUI 中时,也就是不是单独的 window,它不会显示它。我收到的代码警告之一是 "cursor" is not accessedPylance

cursor = Cursor(plot, useblit=True, horizOn=True, vertOn=True, color="green", linewidth=2.0)

我的剧情部分代码:

        figure = Figure(figsize=(5, 4), dpi=100)
        plot = figure.add_subplot(1, 1, 1)
        figure.suptitle(Date, fontsize=12)
        plot.plot(x, y, color=Color)                                

        canvas = FigureCanvasTkAgg(figure, root)
        canvas.get_tk_widget().place(x=4,y=200)

        
        toolbar = NavigationToolbar2Tk(canvas, root, pack_toolbar=False)
        toolbar.update()
        toolbar.place(x=4,y=600)

        cursor = Cursor(plot, useblit=True, horizOn=True, vertOn=True, color="green", linewidth=2.0)

如果不查看所有内容很难说,但我的猜测是 Cursor class 未导入或者您正在分配 光标 变量并且从不使用它。

由于 Cursor 继承自 AxesWidget 并且根据 document of AxesWidget:

To guarantee that the widget remains responsive and not garbage-collected, a reference to the object should be maintained by the user.

因此,如果您的代码在函数内部,那么您需要保留游标的引用。尝试:

plot.cursor = Cursor(plot, useblit=True, horizOn=True, vertOn=True, color="green", linewidth=2.0)

它使用plot的属性来保存游标的引用。