python tkinter canvas when rectangle clicked

若如初见. 提交于 2020-08-19 11:51:29

问题


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?


回答1:


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()


来源:https://stackoverflow.com/questions/42175815/python-tkinter-canvas-when-rectangle-clicked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!