Fail to detect when a key is pressed

Psychopy version : 2021.2.3

Hello everyone,
(sorry for bad english)

I’m trying to create a feedback for my participants to see if they answered the task.
They see a stimulus (it’s an image file) displayed a fix amount of time, and they have to respond by pressing the key L or S (for yes or no). I would like that when they press one of the response key, the opacity of the image change.

So I create a variable ‘opacity’ that I put in the properties of my image and I need a code to detect if a key is pressed to change it. I checked on topics and find some codes but it did not work for me.

I’ve tried this :

In begin experiment :

opacity = 1

In begin routine

kb = keyboard.Keyboard()

In Each Frame

key_pressed = kb.getKeys(['s','l'], waitRelease=False, clear=False)

if key_pressed :
    opacity = 0.5

I think my code does not detect if a key is press. Does someone have an idea of what code I should do instead ?

Thanks a lot !

Hey margaux, have you tried running the keyboard input demo? I like to start there when coding a new feature. If the demo works and your code doesn’t, then you know the problem is with your code.

Also note that if you don’t have a psychopy window open, or if you somehow alt-tabbed or clicked on another window, it won’t work.


if key_pressed.keys :
    opacity = 0.5

@SDAMcIntyre Thank for the advice, I didn’t notice the demo part in Psychopy, i’m quite new with it. But i’ve tried the keyboard demo and it worked so i just used the same code in my experiment to detect the key and it work !!

so I use :

key_pressed = event.getKeys('l','s') 

instead of

key_pressed = kb.getKeys(['s','l'], waitRelease=False, clear=False)

@wakecarter It doesn’t work it returns an error, but in case, I found which code to use with the demo, see above !

Thanks you a lot both of you !

1 Like