![](/img/trans.png)
[英]How to find which Canvas item is closer to the point clicked in tkinter?
[英]How can i see in which tkinter canvas shape is clicked?
我有一个简单的程序,有些按钮不是Tkinter自己制作的。 我只是用canvas.create_rectangle
和类似的东西制作了它们。 但是问题是:按钮可以移动。 我可以这样:
if event.x > c.coords(button)[0] and event.y > c.coords(button)[1] \
and event.x < c.coords(button)[2] and event.y < c.coords(button)[3]:
::line of code::
但是有更短的方法吗? 谢谢!
您可以使用标签绑定: canvas.tag_bind(<tag>, '<1>', callback)
,只需将<tag>
替换为按钮的项目ID。 这是一个例子:
import tkinter as tk
def on_click(event):
print('click')
canvas.move(button1, 10, 5)
root = tk.Tk()
canvas = tk.Canvas(root)
canvas.pack()
button1 = canvas.create_rectangle(10, 10, 50, 50, fill='red')
canvas.tag_bind(button1, '<1>', on_click)
root.mainloop()
您可以使用canvas标签current
,它指定光标下的项目。 从官方的tcl / tk文档中:
标签电流由Tk自动管理; 它适用于当前项目,它是最上面的项目,其绘制的区域覆盖了鼠标光标的位置(不同的项目类型以不同的方式解释此问题;有关详细信息,请参见各个项目类型文档)。 如果鼠标不在画布小部件中或不在项目上方,则没有项目具有当前标签。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.