Keyboard input in code

OS (e.g. Win10): OSX 13.4(Ventura)
PsychoPy version (e.g. 1.84.x): v2022.2.5
Standard Standalone? (y/n) If not then what?: y
What are you trying to achieve?: Process keyboard input in code.

This should be incredibly simple – but I am struggling with this.

All I want to do is capture keystrokes and then, in code, do things.


If key ‘X’ is pressed
** Do stuff**

I have scoured my 3-day intensive course notes, the Psychopy manual, pumped endless search terms in to the forums, watched youtube videos and… I can’t find something that works.

Can anyone help just suggesting the Python code that will allow this?

Various notes on approaches I have tried below.

Ok so I tried using the code found here: Keyboard — PsychoPy v2023.2.3

But found almost every single line would cause a ‘syntax error’ and crashed out when I tried to run – so I’m guessing this code is designed to be inserted into the back end code? Don’t know – but almost every line of this code causes Psychopy to crash.

Have also tried using version of code from here: Keyboard polling

This works – occasionally. But I need to press the key several times for it to sometimes work.

if key_resp.getKeys(keyList=['1']):
    textFeedback.text = "1"
    print("Key 1 pressed")

This also works – but… once I hit a key it seems to continually execute the conditional statement resulting in a constant stream of events. I only want one.

if key_resp.keys == "1":
    Feedback.text = "1"
if key_resp.keys == "2":
    Feedback.text = "2"

I am baffled.

The way I approach this is to add a keyboard component that saves all key presses and then check whether the length of the list of keys has increased. Since len(x) will give an error if x does not exist I have to first check if x:

Begin Routine

nKeys = 0

Each Frame

if key_resp.keys:
     if len(key_resp.keys) > nKeys:
          nKeys = key_resp.keys
          if key_resp.keys[-1] == 'a':
               Do stuff
          elif key_resp.keys[-1] == 'b':
               Do other stuff

Hi @wakecarter!

Again - thanks for getting into this.

Will try that approach.