如何将多个 canvas 元素绑定在一起以同时更改它们的颜色?

How can I bind multiple canvas elements together in order to change their color simultaneously?

所以,这些是我的行 created/drawn:

from tkinter import *


root = Tk()

f= Frame(root)
f.pack()
c = Canvas(f,bg = "black")
c.pack()
line1 = c.create_line(10,0,10,50,fill = "white",activefill = "blue",tag = "one")
line_side1 = c.create_line(0,25,10,25,fill= "white", activefill = "blue",tag = "one")
line2 = c.create_line(30,0,30,50,fill = "white",activefill = "blue",tag = "one")
line_side2 = c.create_line(30,25,40,25,fill= "white", activefill = "blue",tag = "one")
c.pack()

root.mainloop()

所以,现在我希望当我将鼠标悬停在它们上面时,所有的线都应该变成蓝色。

我试过使用 tag_bind 选项,但如果您能告诉我如何操作,将会很有帮助。

我认为您需要做的就是列出所有行 ID(第 1 行、第 2 行、..),悬停时只需更改列表中所有项目的颜色。

from tkinter import *

def set_color(event):
    for x in all_ids:
        c.itemconfig(x, fill="blue")
    return

def return_color(event):
    for x in all_ids:
        c.itemconfig(x, fill="white")
    return

all_ids = []

root = Tk()
f = Frame(root)
f.pack()
c = Canvas(f, bg="black")
c.pack()

all_ids.append(c.create_line(10, 0, 10, 50, fill="white"))
all_ids.append(c.create_line(0, 25, 10, 25, fill="white"))
all_ids.append(c.create_line(30, 0, 30, 50, fill="white"))
all_ids.append(c.create_line(30, 25, 40, 25, fill="white"))


for x in all_ids:
    c.tag_bind(x, '<Enter>', set_color)
    c.tag_bind(x, '<Leave>', return_color)

root.mainloop()

虽然@AleksanderMonk 的回答很好,但我认为在这种情况下绑定到标签 "one" 会更容易,尤其是当您计划制作更多行时。您可以在 tag_binditemconfigure 函数中使用标签而不是 id:

from tkinter import *

def change_color(event):
    if event.type == "7":   # Enter
        event.widget.itemconfigure("one", fill="blue")
    elif event.type == "8": # Leave
        event.widget.itemconfigure("one", fill="white")

root = Tk()
f = Frame(root)
c = Canvas(f, bg="black")
f.pack()    
c.pack()

line1      = c.create_line(10, 0,10,50, fill="white", tag="one")
line_side1 = c.create_line( 0,25,10,25, fill="white", tag="one")
line2      = c.create_line(30, 0,30,50, fill="white", tag="one")
line_side2 = c.create_line(30,25,40,25, fill="white", tag="one")

c.tag_bind("one", "<Enter>", change_color)
c.tag_bind("one", "<Leave>", change_color)

root.mainloop()