How to bind spacebar key to a certain method in tkinter (python)
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()
You could 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 your drawing function to some top-level element to the <Key>
binding which is triggered whenever a key on the keyboard is pressed. Then, the event object that's passed in has a char
member which contains a string representing the key that was pressed on the keyboard.
The event will only be triggered when the object it's bound to has focus, which is why I'm binding the draw
method to the root
object, since that'll always be in focus.
You can aslo use canvas.bind_all("<space>", yourFunction)
That will listen for events in the whole application and not only on widget.