gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 10:23:57 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com