How to bind events to Tkinter Canvas items?

TkinterPythonGUI-Programming

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(<Button>, callback) 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 <Space> key, it will generate random shapes in the canvas window.

raja
Published on 25-May-2021 08:41:29
Advertisements