Currently working on a robotics project in which I need my raspberry pi to detect keypresses (think of game style - instantaneous and always running). I've looked at using pygame or getch but I'm not really sure which one to use or if I should use either at all. I am sure you can tell that I'm pretty new to python, so I would prefer a simple method of doing this. I need this to be able to run 100% in a console, as I will not be running this app in X-Window. Thanks.
Asked
Active
Viewed 1,407 times
-1
-
1Google "simplest way to detect keypresses in python". Top result (it's not pygame or getch) – Erik Nyquist Jan 02 '17 at 02:27
-
http://stackoverflow.com/questions/34497323/what-is-the-easiest-way-to-detect-key-presses-in-python-3-on-a-linux-machine – furas Jan 02 '17 at 04:45
-
pygame have to create and display window to receive events (ie. pressed keys) from system. – furas Jan 02 '17 at 04:52
1 Answers
0
I'd say Pygame is the way to go.
Here is the documentation link: http://www.pygame.org/docs/
Here is some sample code I threw together in Python 2 (Python 3 should be very similar). Run it, and press the space bar when the window is selected:
import pygame, sys
pygame.init()
screen = pygame.display.set_mode([640,480])
clock = pygame.time.Clock()
while 1:
clock.tick(60) #60 FPS
for event in pygame.event.get:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
print "The Spacebar was pressed."
if event.type == pygame.KEYUP:
if event.key == pygame.K_SPACE:
print "The Spacebar was released."
I haven't been able to test this code, but it should work.
I suggest the book "Hello World!" by Carter and Warren Sande. The book is for Python 2.5, but it works for Python 2.7 as well. It's my favorite Python book, and is fantastic for teaching the basics of Python and Pygame in a fun and entertaining way, and includes the interactive programming of many games. Try typing the code provided by the book, rather than copying and pasting, and you'll learn a lot from it.

Douglas
- 1,304
- 10
- 26