Reputation: 23
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!
Upvotes: 2
Views: 1659
Reputation: 386210
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.
Upvotes: 3
Reputation: 16169
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()
Upvotes: 4