如何在 Tkinter 中将点击事件绑定到 Canvas?

Canvas 小部件无疑是 tkinter 中可用的最强大的小部件。它可用于创建和开发从自定义小部件到完整的用户界面。我们甚至可以绑定点击事件来处理画布及其对象。

示范

在这个例子中,我们将在画布小部件中添加一个图像,并将绑定一个按钮对象以从画布中删除图像。

为了绑定点击事件,我们可以使用tag_bind()方法,使用delete(image object)删除图片。

#Import the required library
from tkinter import*
#Create an instance of tkinter frame
win= Tk()
#Set the geometry
win.geometry("750x280")
#Create an canvas object
canvas= Canvas(win, width= 1000, height= 750)
#Load an image inside the canvas
smiley = PhotoImage(file='smile.gif')
#Create an image in the canvas object
image_item = canvas.create_image((200, 140), image=smiley)
#Bind the Button Event to the Canvas Widget
canvas.tag_bind(image_item, '<Button-1>', lambda e:
canvas.delete(image_item))
canvas.pack()
win.mainloop()
输出结果

执行上面的代码将显示笑脸图像。

现在,在图像上“左键单击”鼠标按钮,它将立即从画布中删除。