Python / Tkinter-识别点击对象 [英] Python/Tkinter - Identify object on click
问题描述
我正在尝试创建一个程序,将单击时的对象颜色从白色更改为黑色,或者将单击之前的颜色从白色更改为黑色。我希望程序仅在对象是矩形时才更改颜色。我该如何实现呢?
I am trying to create a program that changes the object colour on click from white to black or from white to black depending of the previous colour. I would want the program change the colour only if the object is a rectangle. How can I make the this happen?
这是我的代码:
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()
在此代码中,程序将更改任何对象的填充颜色。我希望它仅对矩形进行更改。
In this code the program changes the fill colour for any object. I would want it to change it only for rectangles.
感谢帮助。
推荐答案
以下是此问题的三种常见解决方案:
Here are three common solutions to this problem:
您可以向画布询问对象的类型:
You can ask the canvas for the type of the object:
item_type = cv.type(item)
if item_type == "rectangle":
# this item is a rectangle
else:
# this item is NOT a rectangle
使用标签
另一种解决方案是给每个项目一个或多个标签。然后,您可以查询当前项目的标签。
Using tags
Another solution is to give each item one or more tags. You can then query the tags for the current item.
首先,在要点击的项目上包含一个或多个标签:
First, include one or more tags on the items you want to be clickable:
cv. create_rectangle(80, 80, 100, 100, tags=("clickable",))
下一步,检查您感兴趣的商品上的标签,并查看您的标签是否在该商品的标签集中:
Next, check for the tags on the item you're curious about, and check to see if your tag is in the set of tags for that item:
tags = cv.itemcget(item, "tags")
if "clickable" in tags:
# this item has the "clickable" tag
else:
# this item does NOT have the "clickable" tag
在标签上创建绑定
第三个选择是将绑定附加到标签,而不是整个画布。执行此操作时,仅在单击带有给定标签的项目时才调用函数,从而无需进行任何运行时检查:
Create bindings on tags
A third option is to attach the bindings to the tags rather than the canvas as a whole. When you do this, your function will only be called when you click on item with the given tag, eliminating the need to do any sort of runtime check:
cv.tag_bind("clickable", "<1>", onclick)
这篇关于Python / Tkinter-识别点击对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!