psychopy.org | Reference | Downloads | Github

Change allowable keys during routine

I am using Psychopy2 so that I can collect responses from a participant’s keyboard remotely (this didn’t work in Psychopy3).

In my experiment, I’m collecting multiple responses per trial. A simplified description of the experiment is that the participant presses a key, and an image appears. If they press a different key, another image appears. They can make as many images appear as they want in any order they want.

Once they select a given response, I want that to be removed from allowable keys for the rest of that trial. On the text trial, I want the full list of allowable keys available again.

I am using a mix of code and builder. In builder, I added the following example code to “Each Frame”

keys = event.getKeys(['1','2'])

if '1' in keys:
    img_to_show1=image1.png
    trials.addData('key_pressed',keys)

if '2' in keys:
    img_to_show2=image2.png
    trials.addData('key_pressed',keys)

This is working as I want in terms of the images displaying and the data saving as expected, but what I would like to be able to do is to update the allowable keys depending on which key gets pressed. I don’t want them to be able to press the same key twice in the same trial. So, if they press 1, I want the allowable keys to be only keys = event.getKeys(['2']).

I tried moving keys = event.getKeys(['1','2']) to “Begin Routine” in order to initialize the allowable keys, then doing the following in “Each Frame”:

if '1' in keys:
    img_to_show1=image1.png
    trials.addData('key_pressed',keys)
    keys=event.getKeys(['2'])

if '2' in keys:
    img_to_show2=image2.png
    trials.addData('key_pressed',keys)
    keys=event.getKeys(['1'])

But when I did this, no keyboard presses were accepted. There was no error, it just didn’t respond to anything.

I also tried using the following to initialize the allowable keys:

from psychopy.hardware import keyboard
kb = keyboard.Keyboard()
keys = kb.getKeys(['1', '2'])

but when the experiment launches, I get the error:
“ImportError: cannot import name keyboard”
Is this because I’m using PychoPy2?

Any ideas? Thanks in advance!

I would use a flag

Begin Routine

keyPressed=0

Then

if “1” in keys and keyPressed != 1:
     keyPressed=1

Etc

This would allow them to keep alternating but what else you want depends on the rest of the routine.