[英]How can i see in which tkinter canvas shape is clicked?
I have a simple program, with some buttons who are not made by Tkinter self. 我有一个简单的程序,有些按钮不是Tkinter自己制作的。 I just made them with canvas.create_rectangle
and things like that. 我只是用canvas.create_rectangle
和类似的东西制作了它们。 But the problem is: The buttons can move. 但是问题是:按钮可以移动。 I can do it like this: 我可以这样:
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::
But is there a shorter way? 但是有更短的方法吗? Thanks! 谢谢!
You can use tag binding: canvas.tag_bind(<tag>, '<1>', callback)
, just replace <tag>
by the item id of your button. 您可以使用标签绑定: canvas.tag_bind(<tag>, '<1>', callback)
,只需将<tag>
替换为按钮的项目ID。 Here is an example: 这是一个例子:
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()
You can use the canvas tag current
, which specifies the item under the cursor. 您可以使用canvas标签current
,它指定光标下的项目。 From the official tcl/tk documentation: 从官方的tcl / tk文档中:
The tag current is managed automatically by Tk; 标签电流由Tk自动管理; it applies to the current item, which is the topmost item whose drawn area covers the position of the mouse cursor (different item types interpret this in varying ways; see the individual item type documentation for details). 它适用于当前项目,它是最上面的项目,其绘制的区域覆盖了鼠标光标的位置(不同的项目类型以不同的方式解释此问题;有关详细信息,请参见各个项目类型文档)。 If the mouse is not in the canvas widget or is not over an item, then no item has the current tag. 如果鼠标不在画布小部件中或不在项目上方,则没有项目具有当前标签。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.