简体   繁体   中英

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. I just made them with canvas.create_rectangle and things like that. 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. 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. From the official tcl/tk documentation:

The tag current is managed automatically by 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM