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.
JavaScript
x
14
14
1
from tkinter import *
2
3
window = Tk()
4
5
root = Canvas(window, width=500, height=500)
6
7
def testing():
8
print("Hello World!")
9
10
root.bind_all('<Any>', testing)
11
12
root.pack()
13
root.mainloop()
14
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()
.
JavaScript
1
23
23
1
from tkinter import *
2
3
window = Tk()
4
5
root = Canvas(window, width=500, height=500)
6
7
def testing(event):
8
print("Hello!")
9
10
def countdown(count, label):
11
label['text'] = count
12
if count > -1:
13
root.after(1000, countdown, count-1, label)
14
elif count == 0:
15
label['text'] = 'Time Expired'
16
elif count < 0:
17
label.destroy()
18
19
root.bind_all('<Key>', testing)
20
21
root.pack()
22
root.mainloop()
23