How to bind spacebar key to a certain method in tkinter (python)

前端 未结 3 1416
萌比男神i
萌比男神i 2020-12-19 01:44

I am working on a project in python, and I made a method to draw a specific thing in tkinter. I want it so that whenever I press the spacebar, the image will redraw itself (

3条回答
  •  醉梦人生
    2020-12-19 02:28

    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('', draw)
    
    canvas.pack()
    root.mainloop()
    

    Basically, you bind your drawing function to some top-level element to the 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.

提交回复
热议问题