| Reference | Downloads | Github

Change text presented onscreen after every keypress

OS: Win 10
Version: 2020.2.10
Standard Standalone: yes

I’m trying to develop a task in which a number is presented onscreen, and participants have to make a judgement about it (e.g. odd or even?) and press a response key. Once they press the key, the number should be replaced by a new (randomly drawn) number, and so on. This should continue for a pre-determined amount of time (e.g. 5 seconds), no matter how many responses they make. Ideally this should all be enclosed within one routine.

So far I have a simple routine set up with a code segment code, a text stim number, and a key press resp_1, shown below. Note that the Text field of number is defined as $rand_value, and it has a duration of 5.0 seconds. Also note that Force end of Routine is unchecked in resp_1

EDIT: I have changed number to “set every frame” instead of “set every repeat”

The Begin Routine tab of code contains a line which generates a random value to be shown onscreen at the start of the trial.

In the Each Frame tab, I used the following to try and reset rand_value following each button press

This doesn’t cause any errors, but the first generated number (I assume from the Begin Routine tab) simply displays onscreen for 5 s and does not change, regardless of key presses. I need it to change with every key press, but I can’t figure out how to do that.

Any advice would be greatly appreciated!

I am not sure about the code, but it seems that your text component is set to update “every repeat”, it should be set to update “every frame” to work

Ah, good point! I’ve made that change…hasn’t fixed the issue, but it was probably a necessary first step!

Then instead of using a keyboard component, try implementing a keyboard response in the code component, like:

#In the each frame tab
myKeyPress = event.getKeys('return') #you can swap "return" for any key
if 'return' in myKeyPress: # when RETURN is pressed 
     #write here the code to change the text

It works!! Thanks so much!

For future users, the code I used to change the text was: rand_value = random.randint(0,100). Therefore, the full segment in the “Each Frame” tab looks like:

myKeyPress = event.getKeys('return') 
if 'return' in myKeyPress:
    rand_value = random.randint(0,100)

…but note that you still need to have rand_value = random.randint(0,100) in the “Begin Routine” tab. If you need to add multiple keys (e.g. left and right) I found that the following works (as an alternative to the above segment):

myKeyPress = event.getKeys(['left','right']) 
if 'left' in myKeyPress:
    rand_value = random.randint(0,100)
elif 'right' in myKeyPress:
    rand_value = random.randint(0,100)