我正在尝试创建一个程序,根据先前的颜色,将单击时的对象颜色从白色更改为黑色或从白色更改为黑色。我希望程序仅在对象是矩形时才更改颜色。我怎样才能做到这一点?
这是我的代码:
import tkinter as tk
root = tk.Tk()
cv = tk.Canvas(root, height=800, width=800)
cv.pack()
def onclick(event):
item = cv.find_closest(event.x, event.y)
current_color = cv.itemcget(item, 'fill')
if current_color == 'black':
cv.itemconfig(item, fill='white')
else:
cv.itemconfig(item, fill='black')
cv.bind('<Button-1>', onclick)
cv.create_line(50, 50, 60, 60, width=2)
cv. create_rectangle(80, 80, 100, 100)
root.mainloop()
在此代码中,程序更改任何对象的填充颜色。我希望它只针对矩形进行更改。
感谢您的帮助。
请您参考如下方法:
以下是此问题的三种常见解决方案:
使用项目类型
你可以向 Canvas 询问对象的类型:
item_type = cv.type(item)
if item_type == "rectangle":
# this item is a rectangle
else:
# this item is NOT a rectangle
使用标签
另一种解决方案是为每个项目提供一个或多个标签。然后您可以查询当前项目的标签。
首先,在您希望可点击的项目上添加一个或多个标签:
cv. create_rectangle(80, 80, 100, 100, tags=("clickable",))
接下来,检查您感兴趣的项目上的标签,并检查您的标签是否在该项目的标签集中:
tags = cv.itemcget(item, "tags")
if "clickable" in tags:
# this item has the "clickable" tag
else:
# this item does NOT have the "clickable" tag
在标签上创建绑定(bind)
第三种选择是将绑定(bind)附加到标签而不是整个 Canvas 。当你这样做时,你的函数只会在你点击带有给定标签的项目时被调用,无需进行任何类型的运行时检查:
cv.tag_bind("clickable", "<1>", onclick)
