python - 如何将多个 Canvas 元素绑定(bind)在一起以同时更改它们的颜色?

标签 python user-interface tkinter tkinter-canvas

所以,这些是我创建/绘制的线条:

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 选项,但如果您能告诉我如何操作,将会很有帮助。

最佳答案

虽然@AleksanderMonk 的回答很好,但我认为在这种情况下绑定(bind)到标签 "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()

关于python - 如何将多个 Canvas 元素绑定(bind)在一起以同时更改它们的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30612264/

相关文章:

python - Django 管理员 : add inlines dynamically

python - 基于列表在python numpy中排列数据的最快方法

java - 更改后我应该重画GUI吗?

Python - Tkinter 我的条目不显示

python - 值错误: time data '67:01' does not match format '%M:%S'

Python 代码未显示所需的输出但仍在运行

javascript - 通过JQuery选择li元素的文本

java - 实现一个负责创建和存储对象的 “manager”类

python - 对话框中的用户输入

python - Tkinter Canvas 和带网格的滚动条