pythoneventspsychopyexperimental-design

Moving on to another stimulus whenever a key is pressed


I'm setting up an experiment on psychopy in which a stimulus is displayed on the screen for a set period of time (say 0.5s), after which a blank screen is presented with a fixation. I'm using event.waitKeys() in order to get Keyboard input.

I have written the following code.

for i in range (1, 21):
    answer = cf.Stimulus() #This is a function for generating the stimulus
    img = visual.ImageStim(
        win=win,
        image="temp.jpg",
        units="pix"
    )

    img.draw()             #This is the first screen
    fixation.draw()
    win.flip()
    core.wait(0.5)

    fixation.draw()        #This is the second screen
    win.flip()
    keysarray = event.waitKeys()
    os.remove('temp.jpg')

The problem which I'm running into here is that, if the keyboard input has been received before the wait time of 0.5 ends in the first screen, events.waitKeys() doesn't register this key entry and still waits on the second screen for the keyboard input. The program only moves forward if a key entry is received for the second screen.

Instead, I want the program to go to the next stimulus whenever a keyboard input is presented between the start of screen 1 to the end of screen 2. That is, if the keyboard input is received in screen 1 itself (before the end of 0.5s), I want the input to be registered and the program to move on to the next stimulus (either by moving to screen 2 for a very short duration of time, or by skipping screen 2 all together). I can't seem to figure out how this can be achieved.


Solution

  • The short answer here is that event.waitKeys() defaults to clearing the event queue, so that only new keypresses are detected. You can get the behaviour you want by overriding that:

    keysarray = event.waitKeys(clearEvents=False)
    

    But I think that keys pressed prior to calling the function would not have useful reaction times recorded (although keyboard handling has changed a lot in version 3.1).

    Having said that, there are a bunch of other issues with this code that could be improved to fit a more optimal PsychoPy style. I'd suggest posting it at the user forum at https://discourse.psychopy.org. That forum is better suited to back-and-forth discussions than the single question/answer format here at SO.