Python tkinter画布:矩形点击事件

11

我一直在尝试着当我点击tk画布上的一个矩形时运行一个函数。

这是代码:

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

有人知道我应该做什么吗?


你尝试过使用画布 bind 方法吗? - Bryan Oakley
请查看此处的.tag_bind方法:http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/canvas-methods.html - j_4321
1个回答

19

您可以在要绑定事件的项目上添加标签。
您想要的事件是<Button-1>,它是左键单击事件。
要将其应用于您的示例,可以像这样操作:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接