How to associate a space key with a specific method in tkinter (python)

I am working on a project in python and I made a method for drawing a specific thing in tkinter. I want that whenever I press the space bar, the image will be redrawn (run the method again, because I encoded the method so that it can be redrawn above myself). How exactly should I attach a space to a method so that the program starts, draws and re-draws if I press the spacebar?

For example, I want that whenever I press the spacebar, the program draws a random location on the canvas:

from Tkinter import * from random import * root=Tk() canvas=Canvas(root,width=400,height=300,bg='white') def draw(): canvas.delete(ALL)# clear canvas first canvas.create_oval(randint(0,399),randint(0,299),15,15,fill='red') draw() canvas.pack() root.mainloop() 

how would you associate a space with a method?

+7
source share
3 answers
 from Tkinter import * from random import * root=Tk() canvas=Canvas(root,width=400,height=300,bg='white') def draw(event=None): canvas.delete(ALL)# clear canvas first canvas.create_oval(randint(0,399),randint(0,299),15,15,fill='red') draw() canvas.pack() root.bind("<space>", draw) root.mainloop() 
+9
source

You can do something like this:

 from Tkinter import * from random import * root=Tk() canvas=Canvas(root,width=400,height=300,bg='white') def draw(event): if event.char == ' ': canvas.delete(ALL)# clear canvas first canvas.create_oval(randint(0,399),randint(0,299),15,15,fill='red') root.bind('<Key>', draw) canvas.pack() root.mainloop() 

Basically, you bind the drawing function to a top-level element to a <Key> binding, which is triggered whenever a key is pressed on the keyboard. Then, the event object that passed inside has a char member that contains a string representing the key that was pressed on the keyboard.

An event is fired only when the object attached to the object has focus, so I attach the draw method to the root object, since it will always be in focus.

+1
source

You can also use canvas.bind_all("<space>", yourFunction) This will listen for events throughout the application, not just widgets.

0
source

All Articles