Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect key input in Python

(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' or actually any key? How can I do this:

print('You pressed %s' % key)

This should be included in python core, so please do not link modules not related for core python.

like image 747
Velocity-plus Avatar asked Jul 23 '13 16:07

Velocity-plus


People also ask

How do you check key inputs?

The Windows on-screen keyboard is a program included in Windows that shows an on-screen keyboard to test modifier keys and other special keys. For example, when pressing the Alt , Ctrl , or Shift key, the On-Screen Keyboard highlights the keys as pressed.

How do you check if enter key is pressed in Python?

exit(0) #exit program ''' #(not user_input) checks if user has pressed enter key without entering # number. #(int(user_input)<=0) checks if user has entered any number less than or #equal to zero.

How do you wait for keyboard input in Python?

Python wait for user input We can use input() function to achieve this. In this case, the program will wait indefinitely for the user input. Once the user provides the input data and presses the enter key, the program will start executing the next statements. sec = input('Let us wait for user input.

How does Python detect multiple key presses?

You could try using and : while keypressed('w') and keypressed('a'): . As for detecting if the key is released, like the keypressed , you can use the keyrelease .


1 Answers

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()
like image 91
unutbu Avatar answered Sep 25 '22 03:09

unutbu