python tkinter canvas when rectangle clicked

后端 未结 1 350
名媛妹妹
名媛妹妹 2021-01-18 01:47

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(         


        
1条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-18 02:43

    You can add tags on the items you want to bind events to.
    The event you want here is , 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","",clicked)
    
    c.pack()
    
    window.mainloop()
    

    0 讨论(0)
提交回复
热议问题