- Trending Categories
- Data Structure
- Operating System
- C Programming
- 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.
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()
Run the above code to display a window that generates random shapes while pressing the <Space> Key on the Keyboard.
- How to bind the Enter key to a tkinter window?
- How to bind a key to a button in Tkinter?
- How to bind the Escape key to close a window in Tkinter?
- How do I bind the enter key to a function in Tkinter?
- How to bind to shift+tab in Tkinter?
- How to bind all the number keys in Tkinter?
- How to bind a click event to a Canvas in Tkinter?
- How to bind multiple events with one "bind" in Tkinter?
- How to bind events to Tkinter Canvas items?
- How to bind a Tkinter event to the left mouse button being held down?
- How to set the border color of certain Tkinter widgets?
- How to change the color of certain words in a Tkinter text widget?
- ReactJS – bind() method
- How to show the status of CAPS Lock Key in tkinter?
- How to set a certain number of rows and columns of a Tkinter grid?