How to bind the spacebar key to a certain method in Tkinter?

Tkinter methods can be bound with the Keys or Mouse to perform certain operations or events in an application. Let us suppose for a particular application, we want to bind the <Space> Key such that it will perform a certain operation. We can bind any key to a particular operation or event by defining the bind(<key>, callback) method.


In this example, we will create rectangles of random width and height by using random Module in Python. So, whenever we will press the Key, it will generate some random shapes on the screen.

#Import the required Libraries
from tkinter import *
import random

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

#Crate a canvas
def draw_shapes(e):

canvas.create_rectangle(random.randint(5,300), random.randint(1,300), 25, 25, fill='khaki3')

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


Run the above code to display a window that generates random shapes while pressing the <Space> Key on the Keyboard.