psychopy.org | Reference | Downloads | Github

Text input from Psychopy2 to Psychopy3

OS: Mac Mojave (Version 10.14.6)
PsychoPy version: (psychopy3) 1.74.00 – v2020.1.2

Hi! So I had an undergraduate assistant help me code a study on psychopy2 where participants view a Dutch vocabulary word (previously studied) and they are asked to type what they think the English translation is. We had the code working perfectly on psychopy2 where participants could type freely (even using backspace if needed and pressing ‘ENTER’ to indicate they were ready to submit their response), but I was forced to switch my study over to psychopy3 because COVID-19 forced me to move my in-person study online and psychopy3 has access to pavlovia.

Now that I’m trying to use psychopy3, it errors out as soon as I try to type anything in response to the Dutch vocabulary word.

Here’s the full error I get:


2020-05-11 12:06:14.681 python[72676:3154069] ApplePersistenceIgnoreState: Existing state will not be touched. New state will be written to (null)
Traceback (most recent call last):
File “/Users/mbernhardt3/Desktop/studyRun/2bCuedTest_lastrun.py”, line 334, in
if len(theseKeys[i]) == 1:
TypeError: object of type ‘KeyPress’ has no len()
Alert 4205:Python Syntax Error in ‘End Routine’ tab. See ‘None’ on line number 11 of the ‘End Routine’ tab.
For further info see https://psychopy.org/alerts/4205.html

Experiment ended.

I’ve tried messing with the code a bit, but I don’t have any formal coding training and the undergrad that helped me develop this graduated. I think this should be a pretty simple solution, but I can’t seem to figure it out. Alternatively, if you know a better way to allow participants to input text responses in psychopy3, I’m open to rebuilding from scratch. Any help from you lovely forum people would be greatly appreciated! I’m also happy to answer any questions about how this is formatted in the actual builder if that would help!

I’m pasting the full code pulled from psychopy3 here (there are some comments from my coding helper undergrad in here to explain the reasoning behind things, much of this was coded in the ‘code’ component in the routines):


#!/usr/bin/env python

-- coding: utf-8 --

“”"
This experiment was created using PsychoPy3 Experiment Builder (v2020.1.2),
on Mon May 11 12:09:58 2020
If you publish work using this script the most relevant publication is:

Peirce J, Gray JR, Simpson S, MacAskill M, Höchenberger R, Sogo H, Kastman E, Lindeløv JK. (2019) 
    PsychoPy2: Experiments in behavior made easy Behav Res 51: 195. 
    https://doi.org/10.3758/s13428-018-01193-y

“”"

from future import absolute_import, division

from psychopy import locale_setup
from psychopy import prefs
from psychopy import sound, gui, visual, core, data, event, logging, clock
from psychopy.constants import (NOT_STARTED, STARTED, PLAYING, PAUSED,
STOPPED, FINISHED, PRESSED, RELEASED, FOREVER)

import numpy as np # whole numpy lib is available, prepend ‘np.’
from numpy import (sin, cos, tan, log, log10, pi, average,
sqrt, std, deg2rad, rad2deg, linspace, asarray)
from numpy.random import random, randint, normal, shuffle
import os # handy system and path functions
import sys # to get file system encoding

from psychopy.hardware import keyboard

Ensure that relative paths start from the same directory as this script

_thisDir = os.path.dirname(os.path.abspath(file))
os.chdir(_thisDir)

Store info about the experiment session

psychopyVersion = ‘2020.1.2’
expName = ‘textInputTest’ # from the Builder filename that created this script
expInfo = {‘session’: ‘001’, ‘participant’: ‘’}
dlg = gui.DlgFromDict(dictionary=expInfo, sortKeys=False, title=expName)
if dlg.OK == False:
core.quit() # user pressed cancel
expInfo[‘date’] = data.getDateStr() # add a simple timestamp
expInfo[‘expName’] = expName
expInfo[‘psychopyVersion’] = psychopyVersion

Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc

filename = thisDir + os.sep + 'data/%s%s’ %(expInfo[‘participant’], expName)

An ExperimentHandler isn’t essential but helps with data saving

thisExp = data.ExperimentHandler(name=expName, version=’’,
extraInfo=expInfo, runtimeInfo=None,
originPath=’/Users/mbernhardt3/Desktop/studyRun/2bCuedTest.py’,
savePickle=True, saveWideText=True,
dataFileName=filename)

save a log file for detail verbose info

logFile = logging.LogFile(filename+’.log’, level=logging.EXP)
logging.console.setLevel(logging.WARNING) # this outputs to the screen, not a file

endExpNow = False # flag for ‘escape’ or other condition => quit the exp
frameTolerance = 0.001 # how close to onset before ‘same’ frame

Start Code - component code to be run before the window creation

Setup the Window

win = visual.Window(
size=[1440, 900], fullscr=True, screen=0,
winType=‘pyglet’, allowGUI=False, allowStencil=False,
monitor=‘testMonitor’, color=[0,0,0], colorSpace=‘rgb’,
blendMode=‘avg’, useFBO=True)

store frame rate of monitor if we can measure it

expInfo[‘frameRate’] = win.getActualFrameRate()
if expInfo[‘frameRate’] != None:
frameDur = 1.0 / round(expInfo[‘frameRate’])
else:
frameDur = 1.0 / 60.0 # could not measure, so guess

create a default keyboard (e.g. to check for escape)

defaultKeyboard = keyboard.Keyboard()

Initialize components for Routine “Instructions”

InstructionsClock = core.Clock()
ISI = clock.StaticPeriod(win=win, screenHz=expInfo[‘frameRate’], name=‘ISI’)
text = visual.TextStim(win=win, name=‘text’,
text=“Please type the English translation of the Dutch word on the screen, pressing ‘enter’ between each word.\n\nIf you are incorrect, the correct translation will immediately be provided.\n\nIf you correctly translate, you will immediately advance to the next word.\n\nDon’t worry about capitalization.\n\nPress ‘space’ to begin.”,
font=‘Arial’,
pos=[0, 0], height=0.1, wrapWidth=None, ori=0,
color=‘white’, colorSpace=‘rgb’, opacity=1,
languageStyle=‘LTR’,
depth=-1.0);
key_resp_2 = keyboard.Keyboard()

Initialize components for Routine “gatherText”

gatherTextClock = core.Clock()
inputText = “”
text_3 = visual.TextStim(win=win, name=‘text_3’,
text=‘default text’,
font=‘Arial’,
pos=[0,0], height=0.3, wrapWidth=None, ori=0,
color=‘white’, colorSpace=‘rgb’, opacity=1,
languageStyle=‘LTR’,
depth=-1.0);
key_resp_3 = keyboard.Keyboard()
text_4 = visual.TextStim(win=win, name=‘text_4’,
text=“Press ‘enter’ when you have made your response.”,
font=‘Arial’,
pos=(0, -0.6), height=0.075, wrapWidth=None, ori=0,
color=‘white’, colorSpace=‘rgb’, opacity=1,
languageStyle=‘LTR’,
depth=-3.0);

Initialize components for Routine “assertFalse”

assertFalseClock = core.Clock()
outputText = “”
text_6 = visual.TextStim(win=win, name=‘text_6’,
text=‘default text’,
font=‘Arial’,
pos=(0, 0), height=0.3, wrapWidth=None, ori=0,
color=‘white’, colorSpace=‘rgb’, opacity=1,
languageStyle=‘LTR’,
depth=-1.0);
text_7 = visual.TextStim(win=win, name=‘text_7’,
text=’+’,
font=‘Arial’,
pos=(0, 0), height=0.3, wrapWidth=None, ori=0,
color=‘white’, colorSpace=‘rgb’, opacity=1,
languageStyle=‘LTR’,
depth=-2.0);

Initialize components for Routine “end”

endClock = core.Clock()
text_2 = visual.TextStim(win=win, name=‘text_2’,
text=‘This concludes this portion of the study.\n\nPlease alert the researcher.’,
font=‘Arial’,
pos=[0, 0], height=0.1, wrapWidth=None, ori=0,
color=‘white’, colorSpace=‘rgb’, opacity=1,
languageStyle=‘LTR’,
depth=0.0);

Create some handy timers

globalClock = core.Clock() # to track the time since experiment started
routineTimer = core.CountdownTimer() # to track time remaining of each (non-slip) routine

------Prepare to start Routine “Instructions”-------

continueRoutine = True

update component parameters for each repeat

key_resp_2.keys = []
key_resp_2.rt = []
_key_resp_2_allKeys = []

keep track of which components have finished

InstructionsComponents = [ISI, text, key_resp_2]
for thisComponent in InstructionsComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, ‘status’):
thisComponent.status = NOT_STARTED

reset timers

t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock=“now”)
InstructionsClock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1

-------Run Routine “Instructions”-------

while continueRoutine:
# get current time
t = InstructionsClock.getTime()
tThisFlip = win.getFutureFlipTime(clock=InstructionsClock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame

# *text* updates
if text.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
    # keep track of start time/frame for later
    text.frameNStart = frameN  # exact frame index
    text.tStart = t  # local t and not account for scr refresh
    text.tStartRefresh = tThisFlipGlobal  # on global time
    win.timeOnFlip(text, 'tStartRefresh')  # time at next scr refresh
    text.setAutoDraw(True)

# *key_resp_2* updates
waitOnFlip = False
if key_resp_2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
    # keep track of start time/frame for later
    key_resp_2.frameNStart = frameN  # exact frame index
    key_resp_2.tStart = t  # local t and not account for scr refresh
    key_resp_2.tStartRefresh = tThisFlipGlobal  # on global time
    win.timeOnFlip(key_resp_2, 'tStartRefresh')  # time at next scr refresh
    key_resp_2.status = STARTED
    # keyboard checking is just starting
    waitOnFlip = True
    win.callOnFlip(key_resp_2.clock.reset)  # t=0 on next screen flip
    win.callOnFlip(key_resp_2.clearEvents, eventType='keyboard')  # clear events on next screen flip
if key_resp_2.status == STARTED and not waitOnFlip:
    theseKeys = key_resp_2.getKeys(keyList=['space'], waitRelease=False)
    _key_resp_2_allKeys.extend(theseKeys)
    if len(_key_resp_2_allKeys):
        key_resp_2.keys = _key_resp_2_allKeys[-1].name  # just the last key pressed
        key_resp_2.rt = _key_resp_2_allKeys[-1].rt
        # a response ends the routine
        continueRoutine = False
# *ISI* period
if ISI.status == NOT_STARTED and t >= 0.0-frameTolerance:
    # keep track of start time/frame for later
    ISI.frameNStart = frameN  # exact frame index
    ISI.tStart = t  # local t and not account for scr refresh
    ISI.tStartRefresh = tThisFlipGlobal  # on global time
    win.timeOnFlip(ISI, 'tStartRefresh')  # time at next scr refresh
    ISI.start(0.5)
elif ISI.status == STARTED:  # one frame should pass before updating params and completing
    ISI.complete()  # finish the static period

# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
    core.quit()

# check if all components have finished
if not continueRoutine:  # a component has requested a forced-end of Routine
    break
continueRoutine = False  # will revert to True if at least one component still running
for thisComponent in InstructionsComponents:
    if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
        continueRoutine = True
        break  # at least one component has not yet finished

# refresh the screen
if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
    win.flip()

-------Ending Routine “Instructions”-------

for thisComponent in InstructionsComponents:
if hasattr(thisComponent, “setAutoDraw”):
thisComponent.setAutoDraw(False)
thisExp.addData(‘ISI.started’, ISI.tStart)
thisExp.addData(‘ISI.stopped’, ISI.tStop)
thisExp.addData(‘text.started’, text.tStartRefresh)
thisExp.addData(‘text.stopped’, text.tStopRefresh)

check responses

if key_resp_2.keys in [’’, [], None]: # No response was made
key_resp_2.keys = None
thisExp.addData(‘key_resp_2.keys’,key_resp_2.keys)
if key_resp_2.keys != None: # we had a response
thisExp.addData(‘key_resp_2.rt’, key_resp_2.rt)
thisExp.addData(‘key_resp_2.started’, key_resp_2.tStartRefresh)
thisExp.addData(‘key_resp_2.stopped’, key_resp_2.tStopRefresh)
thisExp.nextEntry()

the Routine “Instructions” was not non-slip safe, so reset the non-slip timer

routineTimer.reset()

set up handler to look after randomisation of conditions etc

trials = data.TrialHandler(nReps=1, method=‘random’,
extraInfo=expInfo, originPath=-1,
trialList=data.importConditions(‘allBlocks.csv’),
seed=None, name=‘trials’)
thisExp.addLoop(trials) # add the loop to the experiment
thisTrial = trials.trialList[0] # so we can initialise stimuli with some values

abbreviate parameter names if possible (e.g. rgb = thisTrial.rgb)

if thisTrial != None:
for paramName in thisTrial:
exec(’{} = thisTrial[paramName]’.format(paramName))

for thisTrial in trials:
currentLoop = trials
# abbreviate parameter names if possible (e.g. rgb = thisTrial.rgb)
if thisTrial != None:
for paramName in thisTrial:
exec(’{} = thisTrial[paramName]’.format(paramName))

# ------Prepare to start Routine "gatherText"-------
continueRoutine = True
# update component parameters for each repeat
theseKeys=""
shift_flag = False
text_3.alignHoriz = 'left'
assertFalse = False
text_3.setPos([-.5, 0])
key_resp_3.keys = []
key_resp_3.rt = []
_key_resp_3_allKeys = []
# keep track of which components have finished
gatherTextComponents = [text_3, key_resp_3, text_4]
for thisComponent in gatherTextComponents:
    thisComponent.tStart = None
    thisComponent.tStop = None
    thisComponent.tStartRefresh = None
    thisComponent.tStopRefresh = None
    if hasattr(thisComponent, 'status'):
        thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
gatherTextClock.reset(-_timeToFirstFrame)  # t0 is time of first possible flip
frameN = -1

# -------Run Routine "gatherText"-------
while continueRoutine:
    # get current time
    t = gatherTextClock.getTime()
    tThisFlip = win.getFutureFlipTime(clock=gatherTextClock)
    tThisFlipGlobal = win.getFutureFlipTime(clock=None)
    frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
    # update/draw components on each frame
    n= len(theseKeys)
    i = 0
    escapeRoutine = False
    
    while i < n:
        if theseKeys[i] == '9':
            continueRoutine = False
            escapeRoutine = True
            break
    
        if theseKeys[i] == 'return':
            # pressing RETURN means time to stop
            continueRoutine = False
            break
    
        elif theseKeys[i] == 'backspace':
            inputText = inputText[:-1]  # lose the final character
            i = i + 1
    
        elif theseKeys[i] == 'space':
            inputText += ' '
            i = i + 1
    
        elif theseKeys[i] in ['lshift', 'rshift']:
            shift_flag = True
            i = i + 1
    
        else:
            if len(theseKeys[i]) == 1:
                # we only have 1 char so should be a normal key, 
                # otherwise it might be 'ctrl' or similar so ignore it
                if shift_flag:
                    inputText += chr( ord(theseKeys[i]) - ord(' '))
                    shift_flag = False
                else:
                    inputText += theseKeys[i]
    
            i = i + 1
    
    
    
    
    
    
    # *text_3* updates
    if text_3.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
        # keep track of start time/frame for later
        text_3.frameNStart = frameN  # exact frame index
        text_3.tStart = t  # local t and not account for scr refresh
        text_3.tStartRefresh = tThisFlipGlobal  # on global time
        win.timeOnFlip(text_3, 'tStartRefresh')  # time at next scr refresh
        text_3.setAutoDraw(True)
    if text_3.status == STARTED:  # only update if drawing
        text_3.setText(DUTCH + " " + inputText, log=False)
    
    # *key_resp_3* updates
    waitOnFlip = False
    if key_resp_3.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
        # keep track of start time/frame for later
        key_resp_3.frameNStart = frameN  # exact frame index
        key_resp_3.tStart = t  # local t and not account for scr refresh
        key_resp_3.tStartRefresh = tThisFlipGlobal  # on global time
        win.timeOnFlip(key_resp_3, 'tStartRefresh')  # time at next scr refresh
        key_resp_3.status = STARTED
        # keyboard checking is just starting
        waitOnFlip = True
        win.callOnFlip(key_resp_3.clock.reset)  # t=0 on next screen flip
        win.callOnFlip(key_resp_3.clearEvents, eventType='keyboard')  # clear events on next screen flip
    if key_resp_3.status == STARTED and not waitOnFlip:
        theseKeys = key_resp_3.getKeys(keyList=None, waitRelease=False)
        _key_resp_3_allKeys.extend(theseKeys)
        if len(_key_resp_3_allKeys):
            key_resp_3.keys = [key.name for key in _key_resp_3_allKeys]  # storing all keys
            key_resp_3.rt = [key.rt for key in _key_resp_3_allKeys]
    
    # *text_4* updates
    if text_4.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
        # keep track of start time/frame for later
        text_4.frameNStart = frameN  # exact frame index
        text_4.tStart = t  # local t and not account for scr refresh
        text_4.tStartRefresh = tThisFlipGlobal  # on global time
        win.timeOnFlip(text_4, 'tStartRefresh')  # time at next scr refresh
        text_4.setAutoDraw(True)
    
    # check for quit (typically the Esc key)
    if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
        core.quit()
    
    # check if all components have finished
    if not continueRoutine:  # a component has requested a forced-end of Routine
        break
    continueRoutine = False  # will revert to True if at least one component still running
    for thisComponent in gatherTextComponents:
        if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
            continueRoutine = True
            break  # at least one component has not yet finished
    
    # refresh the screen
    if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
        win.flip()

# -------Ending Routine "gatherText"-------
for thisComponent in gatherTextComponents:
    if hasattr(thisComponent, "setAutoDraw"):
        thisComponent.setAutoDraw(False)
# let's store the final text string into the results finle...
inputText = inputText.upper()
thisExp.addData('inputText', inputText)

if inputText.upper() != ENGLISH:
    print(inputText.upper())
    assertFalse = True

if escapeRoutine:
    trials.finished = True
    break
trials.addData('text_3.started', text_3.tStartRefresh)
trials.addData('text_3.stopped', text_3.tStopRefresh)
# check responses
if key_resp_3.keys in ['', [], None]:  # No response was made
    key_resp_3.keys = None
trials.addData('key_resp_3.keys',key_resp_3.keys)
if key_resp_3.keys != None:  # we had a response
    trials.addData('key_resp_3.rt', key_resp_3.rt)
trials.addData('key_resp_3.started', key_resp_3.tStartRefresh)
trials.addData('key_resp_3.stopped', key_resp_3.tStopRefresh)
trials.addData('text_4.started', text_4.tStartRefresh)
trials.addData('text_4.stopped', text_4.tStopRefresh)
# the Routine "gatherText" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()

# ------Prepare to start Routine "assertFalse"-------
continueRoutine = True
routineTimer.add(6.000000)
# update component parameters for each repeat
outputText = ""
# keep track of which components have finished
assertFalseComponents = [text_6, text_7]
for thisComponent in assertFalseComponents:
    thisComponent.tStart = None
    thisComponent.tStop = None
    thisComponent.tStartRefresh = None
    thisComponent.tStopRefresh = None
    if hasattr(thisComponent, 'status'):
        thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
assertFalseClock.reset(-_timeToFirstFrame)  # t0 is time of first possible flip
frameN = -1

# -------Run Routine "assertFalse"-------
while continueRoutine and routineTimer.getTime() > 0:
    # get current time
    t = assertFalseClock.getTime()
    tThisFlip = win.getFutureFlipTime(clock=assertFalseClock)
    tThisFlipGlobal = win.getFutureFlipTime(clock=None)
    frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
    # update/draw components on each frame
    if assertFalse:
        outputText = ENGLISH
    else:
        continueRoutine = False
    
    # *text_6* updates
    if text_6.status == NOT_STARTED and tThisFlip >= 0.5-frameTolerance:
        # keep track of start time/frame for later
        text_6.frameNStart = frameN  # exact frame index
        text_6.tStart = t  # local t and not account for scr refresh
        text_6.tStartRefresh = tThisFlipGlobal  # on global time
        win.timeOnFlip(text_6, 'tStartRefresh')  # time at next scr refresh
        text_6.setAutoDraw(True)
    if text_6.status == STARTED:
        # is it time to stop? (based on global clock, using actual start)
        if tThisFlipGlobal > text_6.tStartRefresh + 5.5-frameTolerance:
            # keep track of stop time/frame for later
            text_6.tStop = t  # not accounting for scr refresh
            text_6.frameNStop = frameN  # exact frame index
            win.timeOnFlip(text_6, 'tStopRefresh')  # time at next scr refresh
            text_6.setAutoDraw(False)
    if text_6.status == STARTED:  # only update if drawing
        text_6.setText(DUTCH + " " + outputText, log=False)
    
    # *text_7* updates
    if text_7.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
        # keep track of start time/frame for later
        text_7.frameNStart = frameN  # exact frame index
        text_7.tStart = t  # local t and not account for scr refresh
        text_7.tStartRefresh = tThisFlipGlobal  # on global time
        win.timeOnFlip(text_7, 'tStartRefresh')  # time at next scr refresh
        text_7.setAutoDraw(True)
    if text_7.status == STARTED:
        # is it time to stop? (based on global clock, using actual start)
        if tThisFlipGlobal > text_7.tStartRefresh + 0.5-frameTolerance:
            # keep track of stop time/frame for later
            text_7.tStop = t  # not accounting for scr refresh
            text_7.frameNStop = frameN  # exact frame index
            win.timeOnFlip(text_7, 'tStopRefresh')  # time at next scr refresh
            text_7.setAutoDraw(False)
    
    # check for quit (typically the Esc key)
    if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
        core.quit()
    
    # check if all components have finished
    if not continueRoutine:  # a component has requested a forced-end of Routine
        break
    continueRoutine = False  # will revert to True if at least one component still running
    for thisComponent in assertFalseComponents:
        if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
            continueRoutine = True
            break  # at least one component has not yet finished
    
    # refresh the screen
    if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
        win.flip()

# -------Ending Routine "assertFalse"-------
for thisComponent in assertFalseComponents:
    if hasattr(thisComponent, "setAutoDraw"):
        thisComponent.setAutoDraw(False)
inputText = ""
trials.addData('text_6.started', text_6.tStartRefresh)
trials.addData('text_6.stopped', text_6.tStopRefresh)
trials.addData('text_7.started', text_7.tStartRefresh)
trials.addData('text_7.stopped', text_7.tStopRefresh)
thisExp.nextEntry()

completed 1 repeats of ‘trials’

------Prepare to start Routine “end”-------

continueRoutine = True

update component parameters for each repeat

keep track of which components have finished

endComponents = [text_2]
for thisComponent in endComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, ‘status’):
thisComponent.status = NOT_STARTED

reset timers

t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock=“now”)
endClock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1

-------Run Routine “end”-------

while continueRoutine:
# get current time
t = endClock.getTime()
tThisFlip = win.getFutureFlipTime(clock=endClock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame

# *text_2* updates
if text_2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
    # keep track of start time/frame for later
    text_2.frameNStart = frameN  # exact frame index
    text_2.tStart = t  # local t and not account for scr refresh
    text_2.tStartRefresh = tThisFlipGlobal  # on global time
    win.timeOnFlip(text_2, 'tStartRefresh')  # time at next scr refresh
    text_2.setAutoDraw(True)

# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
    core.quit()

# check if all components have finished
if not continueRoutine:  # a component has requested a forced-end of Routine
    break
continueRoutine = False  # will revert to True if at least one component still running
for thisComponent in endComponents:
    if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
        continueRoutine = True
        break  # at least one component has not yet finished

# refresh the screen
if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
    win.flip()

-------Ending Routine “end”-------

for thisComponent in endComponents:
if hasattr(thisComponent, “setAutoDraw”):
thisComponent.setAutoDraw(False)
thisExp.addData(‘text_2.started’, text_2.tStartRefresh)
thisExp.addData(‘text_2.stopped’, text_2.tStopRefresh)

the Routine “end” was not non-slip safe, so reset the non-slip timer

routineTimer.reset()

Flip one final time so any remaining win.callOnFlip()

and win.timeOnFlip() tasks get executed before quitting

win.flip()

these shouldn’t be strictly necessary (should auto-save)

thisExp.saveAsWideText(filename+’.csv’)
thisExp.saveAsPickle(filename)
logging.flush()

make sure everything is closed down

thisExp.abort() # or data files will save again on exit
win.close()
core.quit()

@Mary_Bernhardt, the new keyboard based on PsychToolBox returns a list of keypress objects. KeyPress objects have attributes such as name (of key pressed) and rt. When using the theseKeys list to get a keypress, you want to index the keypress object from the list, and then you can access the attributes of the keypress object. You are receiving the error because the keypress object itself does not have a length, in the same way that a list of objects has a length. The fix is:

if theseKeys[i].name == '1':
   # do something

Or you could check whether theseKeys contains a keypress by first checking the length, and then index and access the keypress object:

if len(theseKeys):
  if theseKeys[i].name == '1':
    # do something

Hey sorry I may have under-emphasized how bad I am at coding… This seems like a straightforward fix but I’m having trouble figuring out where I would make this change in the code. I tried adding ‘.name’ to all the ‘thesekeys [i]’ parts in the ‘if’ statements (I pasted what I did below), but now it’s saying I have a syntax error. I also tried adding the second statement within this if block, but that didn’t work… I’m just -really- not good at coding so I’m probably doing this completely wrong. This is compounded by the fact that I’m working with someone else’s code. I would be so grateful if you would be willing to dumb it down even further for me.

while i < n:
if theseKeys[i].name == ‘1’:
continueRoutine = False
escapeRoutine = True
break

if theseKeys[i].name == 'return':
    # pressing RETURN means time to stop
    continueRoutine = False
    break

elif theseKeys[i].name == 'backspace':
    inputText = inputText[:-1]  # lose the final character
    i = i + 1

elif theseKeys[i].name == 'space':
    inputText += ' '
    i = i + 1

elif theseKeys[i].name in ['lshift', 'rshift']:
    shift_flag = True
    i = i + 1

else:
    if len(theseKeys):
        if theseKeys[i].name == 1:
        # we only have 1 char so should be a normal key, 
        # otherwise it might be 'ctrl' or similar so ignore it
        if shift_flag:
            inputText += chr( ord(theseKeys[i].name) - ord(' '))
            shift_flag = False
        else:
            inputText += theseKeys[i].name

    i = i + 1

I’m facing the exact same issue! Thank you so much for your response. However, it seems for me that the error is with len(theseKeys), with the type error KeyPress has no len(). It totally makes sense that, as you suggested, we cannot treat theseKeys like normal strings. I tried using len(theseKeys.name), but encountered another error that says string does not have attribute name. Do you happen to know how to fix this error? Thank you so much!

You might want to change your code completely, to the following (where you already have a keyboard component called “key_resp”). This is a modified version of textInput demo on Pavlovia, and changes the text of the actual text component (in this example it is called text) :

theseKeys = key_resp.getKeys()

if len(theseKeys):
    if theseKeys[0].name == 'space':
        text.text = text.text + ' '
    elif theseKeys[0].name == 'backspace':
        text.text = text.text[:-1]
    elif theseKeys[0].name in ['lshift', 'rshift']:
        shift_flag = True
    elif theseKeys[0].name == 'return':
        continueRoutine = False
    else:
        if shift_flag:
            text.text = text.text + theseKeys[0].name.upper()
            shift_flag = False
        else:
            text.text = text.text + theseKeys[0].name
1 Like

Ok the error I’m getting now that I’v replaced my old code with what you supplied is below. I can’t find ‘escapeRoutine’ anywhere in my code so I’m not sure where that error is coming from. Line 11 on the End Routine tab is just ‘break’. It’s not blue like the breaks usually are though.

Traceback (most recent call last):
File “/Users/mbernhardt3/Desktop/studyRun/2bCuedTest_Try_lastrun.py”, line 395, in
if escapeRoutine:
NameError: name ‘escapeRoutine’ is not defined
Alert 4205:Python Syntax Error in ‘End Routine’ tab. See ‘None’ on line number 11 of the ‘End Routine’ tab.

@Mary_Bernhardt, you need to define escapeRoutine somewhere, before you use it, preferably at the beginning of the routine. E.g., escapeRoutine = False

So now that I’ve added that, as soon as I get to the screen that prompts me to type a response when running the study, my computer freezes and nothing I type does anything, including escape. I’ve decided to just give you an updated rundown of what the code component of my psychopy looks like:

Note: gatherText has a ‘key_resp’ keyboard component as well
The code component of the initial ‘gatherText’ routine is:

Begin Experiment*
inputText = “”

Begin Routine*
theseKeys=""
shift_flag = False
text_3.alignHoriz = ‘left’
assertFalse = False
escapeRoutine = False

Each Frame*
theseKeys = key_resp.getKeys()

if len(theseKeys):
if theseKeys[0].name == ‘space’:
text.text = text.text + ’ ’
elif theseKeys[0].name == ‘backspace’:
text.text = text.text[:-1]
elif theseKeys[0].name in [‘lshift’, ‘rshift’]:
shift_flag = True
elif theseKeys[0].name == ‘return’:
continueRoutine = False
else:
if shift_flag:
text.text = text.text + theseKeys[0].name.upper()
shift_flag = False
else:
text.text = text.text + theseKeys[0].name

End Routine*

let’s store the final text string into the results finle…

inputText = inputText.upper()
thisExp.addData(‘inputText’, inputText)

if inputText.upper() != ENGLISH:
print(inputText.upper())
assertFalse = True

if escapeRoutine:
trials.finished = True
break

(End Experiment is empty here)

After the ‘gatherText’ routine, it moves to the ‘assertFalse’ routine, which has a code component as well: (Note: this was designed so that after participants press ‘enter’ to submit their response, the code should compare their response to the actual correct response and give tailored feedback, like what would’ve been correct, depending on their typed response)

Begin Experiment*
outputText = “”

Begin Routine*
outputText = “”

Each Frame*
if assertFalse:
outputText = ENGLISH
else:
continueRoutine = False

End Routine*
inputText = “”

(Again, End Experiment is empty)

I just want to take a moment here at the end to say thank you for helping me out! I really appreciate that you’re taking the time to work with me on this! I feel like I’m learning a lot just from troubleshooting.

@Mary_Bernhardt, take a look at this working demo, and see how your code differs. I did have to create a keyboard using code to get this working properly, but everything you need is in the code components.

input.psyexp (7.9 KB)