Making the Return Key Conditional for Text Box Answer

I’m working with this text box code, but I want to make the trial such that the return key will not advance to the next trial until there is text in the response box (i.e., len(keys) > 0). I’ve tried changing this code around in different ways, but haven’t been able to get it to respond to my changes without breaking the whole task. I’m new to Python, so does anyone have input on how I could fix this?

keys = event.getKeys()
if len(keys):
    if 'space' in keys:
        text.text = text.text + ' '
    elif 'backspace' in keys:
        text.text = text.text[:-1]
    elif 'lshift' in keys or 'rshift' in keys:
        modify = True
    elif 'return' in keys:
        continueRoutine = False
    else:
        if modify:
            text.text = text.text + keys[0].upper()
            modify = False
        else:
            text.text = text.text + keys[0]

I’ve the same problem. I’ve used the below coding (in bold) but it doesn’t end the routine. It might work with you.

actualKeys = event.getKeys()
n = len(actualKeys)
i = 0
while i < n:
if actualKeys[i] == ‘return’ and len(inputText3 > 3):
continueRoutine = False
break
elif actualKeys[i] == ‘backspace’:
inputText3 = inputText3[:-1] # lose the final character
i = i + 1
elif actualKeys[i] == ‘space’:
inputText3 += ’ ’
i = i + 1
elif actualKeys[i] in [‘minus’, ‘-’, ‘num_subtract’, ‘Minus’, ‘slash’]:
inputText3 += ‘-’
i = i + 1
elif actualKeys[i] in [‘lshift’, ‘rshift’, ‘SHIFT’]:
shift_flag = True
i = i + 1
else:
if len(actualKeys[i]) == 1:
if shift_flag:
inputText3 += actualKeys[i].upper()
shift_flag = False
else:
inputText3 += actualKeys[i]
i = i + 1

I tried your suggestion, but I receive a “Alert 4205:Python Syntax Error” for the line in bold when I try to run it. I’m not sure why?

Hello @etd17 and @Ghoza_Elottee

I was in a similar situation with a questionnaire at the beginning of my experiment. Twice while piloting I accidentally hit the return key prematurely, and realized how this could become a problem. To fix it I didn’t need to add new variables but did need to add a new if statement and make each of the two if ‘return’ statements conditional to the length of my text variable. In my case, the name of my variable was “text_22”. Here’s how I modified the elif’s for return at the end of the keys code:

     elif len(text_22.text)<=1 and'return' in keys:#if length < 2, return just sits there. protects against accidental enter
        text_22.text = text_22.text
        continueRoutine = True
     elif len(text_22.text)>=2 and 'return' in keys:
        continueRoutine = False

This way return just sits there until the required length is met so the participant has to make an entry. Hope this helps!