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.

Example

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
canvas=Canvas(win,width=500,height=250,bg='white')
def draw_shapes(e):
   canvas.delete(ALL)

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

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

Output

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

Updated on: 04-May-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements