当光标悬停在 Python 中的 canvas 时显示消息 (tkinter)

Display message when the cursor is hovering a canvas in Python (tkinter)

所以我有这些代码行:

from tkinter import *

root = Tk()
root.geometry("400x200")


canvas = Canvas(root, width=150, height=150, bg="black", bd=2, relief="ridge")
canvas.place(x=20, y=20)

A = canvas.create_oval(20,20,30,30, outline='grey', fill="grey")

B = canvas.create_oval(130,130,140,140, outline='grey', fill="grey")

root.mainloop()

我正在尝试了解当我将鼠标悬停在 canvas 上时如何显示文本。例如,当我的鼠标悬停在第一个圆圈上时,文字应该是“A”,而对于第二个圆圈,它应该是“B”。

我找到了一个代码来完成我想做的事情,但它是文本,我不知道如何让它也与 canvas 一起工作:

import tkinter as tk

class Example(tk.Frame):
    def __init__(self, *args, **kwargs):
        tk.Frame.__init__(self, *args, **kwargs)
        self.l1 = tk.Label(self, text="Hover over me")
        self.l2 = tk.Label(self, text="", width=40)
        self.l1.pack(side="top")
        self.l2.pack(side="top", fill="x")

        self.l1.bind("<Enter>", self.on_enter)
        self.l1.bind("<Leave>", self.on_leave)

    def on_enter(self, event):
        self.l2.configure(text="Hello world")

    def on_leave(self, enter):
        self.l2.configure(text="")

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(side="top", fill="both", expand="true")
    root.mainloop()

此外,假设我有另一个 .py 文件,我想在其中为 A 和 B canvases 分配与该 .py 文件不同的变量,并将其显示在文本配置中。例如:在 .py 文件中我有变量

for_A = 123
for_B = 456 

我怎样才能让它看起来像我悬停在 A 上时 canvas 它会显示如下内容:

 A 
123 
  1. 您需要在 canvas.create_oval(...) 中添加 tag 选项:
A = canvas.create_oval(20,20,30,30, outline='grey', fill="grey", tag="A")
B = canvas.create_oval(130,130,140,140, outline='grey', fill="grey", tag="B")
  1. 创建一个标签来显示圈子名称:
lbl = Label(root)
lbl.place(x=200, y=20, anchor="nw")
  1. 使用canvas.tag_bind()绑定两个圈子上的<Enter><Leave>事件:
def on_enter(e):
    # find the canvas item below mouse cursor
    item = canvas.find_withtag("current")
    # get the tags for the item
    tags = canvas.gettags(item)
    # show it using the label
    lbl.config(text=tags[0])

def on_leave(e):
    # clear the label text
    lbl.config(text="")

for item in (A, B):
    canvas.tag_bind(item, "<Enter>", on_enter)
    canvas.tag_bind(item, "<Leave>", on_leave)