How to bind events to Tkinter Canvas items?

Tkinter events can be bound with the widgets to perform a set of operations on the widgets. To be more specific, we can also bind an event handler to Canvas Items by using bind(method. Binding the event with the canvas item makes a canvas item dynamic which can be customized by event handlers.

Example

#Import the required Libraries
from tkinter import *
import random

#Create an instance of Tkinter frame
win = Tk()

#Set the geometry of the window
win.geometry("700x350")

#Crate a canvas
canvas=Canvas(win,width=700,height=350,bg='white')
def draw_shapes(e):
   canvas.delete(ALL)

canvas.create_oval(random.randint(5,300),random.randint(1,300),25,25,fill='O rangeRed2')
canvas.pack()

#Bind the spacebar Key to a function
win.bind("<space>", draw_shapes)
win.mainloop()

Output

Running the above code will display a window that contains a Canvas.

When we press the key, it will generate random shapes in the canvas window.

Updated on: 2021-05-25T08:49:19+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements