11

I've been trying to make a function run when I click a rectangle on a tk canvas.

Here is the code:

from tkinter import * window = Tk() c = Canvas(window, width=300, height=300) def clear(): canvas.delete(ALL) playbutton = c.create_rectangle(75, 25, 225, 75, fill="red") playtext = c.create_text(150, 50, text="Play", font=("Papyrus", 26), fill='blue') c.pack() window.mainloop() 

does anyone know what I should do?

3
  • have you tried using the canvas bind method? Commented Feb 11, 2017 at 14:20
  • Have a look at the .tag_bind method here Commented Feb 11, 2017 at 14:25
  • See also: is it possible to find the canvas shape clicked in a mouse button press event in tkinter?. If you want every item on the canvas to be separately "clickable", then you can instead make the canvas clickable and use the special 'current' tag for the itemconfigure call. This should be much more efficient than making a separate tag for each item, .tag_binding them all and then checking the item ID in the event handler (if that information is even available). Commented Nov 11, 2024 at 17:24

1 Answer 1

19

You can add tags on the items you want to bind events to.
The event you want here is <Button-1>, which is left mousebutton.
To apply this to your example, you can do like this:

from tkinter import Tk, Canvas window = Tk() c = Canvas(window, width=300, height=300) def clear(): canvas.delete(ALL) def clicked(*args): print("You clicked play!") playbutton = c.create_rectangle(75, 25, 225, 75, fill="red",tags="playbutton") playtext = c.create_text(150, 50, text="Play", font=("Papyrus", 26), fill='blue',tags="playbutton") c.tag_bind("playbutton","<Button-1>",clicked) c.pack() window.mainloop() 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.