- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
Advertisements