- 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 events to Tkinter Canvas items?
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.
Advertisements