Skip to content
Advertisement

Keybind that binds to every key in tkinter

I am creating an interactive game with Python, and I am trying to make an introduction with the instruction “Press any key to continue.” I am having some difficulty with binding all the keys to a single action.

I have tried binding to '<Any>', but it displays an error message.

from tkinter import *

window = Tk()

root = Canvas(window, width=500, height=500)

def testing():
    print("Hello World!")

root.bind_all('<Any>', testing)

root.pack()
root.mainloop()

As mentioned before, the '<Any>' keybind results in an error message reading: tkinter.TclError: bad event type or keysym "Any". Is there a simple way to bind every key to an action?

Advertisement

Answer

I use <Key> it will capture any keyboard event and print “Hello”. And don’t forget to specify event or event=None parameter in testing() .

from tkinter import *

window = Tk()

root = Canvas(window, width=500, height=500)

def testing(event):
    print("Hello!")

def countdown(count, label):
    label['text'] = count
    if count > -1:
        root.after(1000, countdown, count-1, label)
    elif count == 0:
        label['text'] = 'Time Expired'
    elif count < 0:
        label.destroy()

root.bind_all('<Key>', testing)

root.pack()
root.mainloop()
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement