| Reference | Downloads | Github

Change text color based on key response

Hello. I’m trying to give visual feedback based on key responses, and I want the color of a text component to change when a participant presses a certain key. I am using psychopy3. I tried using a code component like this:

“Each Frame” Tab. text1 and text2 were defined in the “Begin Routine” tab.

if event.getKeys(['a']):
    text1 = "Red"
    text2 = "Black"
if event.getKeys(['c']):
    text1 = "Black"
    textI2= "Red"

It’s working as i want in my laptop, the text component’s color changes after a key press. I’m not really sure why as i understand that event.getKeys should just return a list of the values of the keypresses rather than a TRUE value. However, in another pc with psychopy3, it is not doing anything most of the time, the text’s color only changes after a key press in a very inconsistent manner.

I also tried:

keypress = event.getKeys(['a','c'])

if keypress == ['a']:
    textDesigual = "Red"
    textIgual = "Black"
elif keypress == ['c']:
    textDesigual = "Black"
    textIgual = "Red"

And it’s working in my laptop, but i haven’t tried it in the other computer to see if get the same error

Any help? sorry if this is a dumb question

You’re right, the function returns a list, but you have that function in an if statement. if will evaluate the result as True or False, and Python happens to regard an empty list as being equivalent to False.

However, that first code sample is not ideal, as you repeat the call to event.getKeys() in quick succession. The result will therefore be very unreliable. If, at the time the code runs, the person has pushed c, then this will often not get detected, because you first check if the a key has been pressed, which empties the queue of any other responses. So the second check will (usually) fail: even if the person pushed c, the first check for a will delete that c response from the queue before you try to check for it.

Your second code sample is much better. There you call the function just once, and store the result so that it can be evaluated as many times as you need. That way it should reliably pick up either response.