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

前端 未结 3 1417
萌比男神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:22
    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()
    
    0 讨论(0)
  • 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('<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.

    0 讨论(0)
  • 2020-12-19 02:36

    You can aslo use canvas.bind_all("<space>", yourFunction) That will listen for events in the whole application and not only on widget.

    0 讨论(0)
提交回复
热议问题