(In 2013) I don\'t know why Python is that weird, you can\'t find this by searching in google very easily, but it\'s quite simple.
How can I detect \'SPACE\
You could make a little Tkinter app:
import Tkinter as tk
def onKeyPress(event):
text.insert('end', 'You pressed %s\n' % (event.char, ))
root = tk.Tk()
root.geometry('300x200')
text = tk.Text(root, background='black', foreground='white', font=('Comic Sans MS', 12))
text.pack()
root.bind('<KeyPress>', onKeyPress)
root.mainloop()
use the builtin: (no need for tkinter)
s = input('->>')
print(s) # what you just typed); now use if's
Key input is a predefined event. You can catch events by attaching event_sequence
(s) to event_handle
(s) by using one or multiple of the existing binding methods(bind
, bind_class
, tag_bind
, bind_all
). In order to do that:
event_handle
methodevent_sequence
) that fits your case from an events listWhen an event happens, all of those binding methods implicitly calls the event_handle
method while passing an Event
object, which includes information about specifics of the event that happened, as the argument.
In order to detect the key input, one could first catch all the '<KeyPress>'
or '<KeyRelease>'
events and then find out the particular key used by making use of event.keysym
attribute.
Below is an example using bind
to catch both '<KeyPress>'
and '<KeyRelease>'
events on a particular widget(root
):
try: # In order to be able to import tkinter for
import tkinter as tk # either in python 2 or in python 3
except ImportError:
import Tkinter as tk
def event_handle(event):
# Replace the window's title with event.type: input key
root.title("{}: {}".format(str(event.type), event.keysym))
if __name__ == '__main__':
root = tk.Tk()
event_sequence = '<KeyPress>'
root.bind(event_sequence, event_handle)
root.bind('<KeyRelease>', event_handle)
root.mainloop()
Use Tkinter there are a ton of tutorials online for this. basically, you can create events. Here is a link to a great site! This makes it easy to capture clicks. Also, if you are trying to make a game, Tkinter also has a GUI. Although, I wouldn't recommend Python for games at all, it could be a fun experiment. Good Luck!