I’m running ito this:
I’ve tried a lot of things and I couldn’t get it to work. I’ve made many changes inside the builder but nothing has worked. Here’s my code and the error informaiton:
Exception has occurred: TypeError
'TextStim' object is not iterable
File "C:\Users\mw24396\Documents\GitHub\DANVA\2_template demographics inside psychopy builder.py", line 388, in <module>
iter(next_button)
which is happening when I run this code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This experiment was created using PsychoPy3 Experiment Builder (v2021.2.3),
on February 03, 2022, at 12:39
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, colors
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, choice as randchoice
import os # handy system and path functions
import sys # to get file system encoding
from psychopy.hardware import keyboard
from PyPDF2 import PdfFileReader, PdfFileWriter
from collections import OrderedDict
from PyPDF2.generic import BooleanObject, NameObject, IndirectObject
expInfo = {'session': '001', 'participant': '', 'age': '', 'gender': '', 'ethnicity': ''}
# This is a before experiment comment in the code section of the readymessage section
# this is a comment "before experiment"
# 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 = '2021.2.3'
expName = 'blockedTrials' # from the Builder filename that created this script
expInfo = {'session': '001', 'participant': '', 'age': '', 'gender': '', 'ethnicity': ''}
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 + u'data/%s_%s_%s' % (expInfo['participant'], expName, expInfo['date'])
# An ExperimentHandler isn't essential but helps with data saving
thisExp = data.ExperimentHandler(name=expName, version='',
extraInfo=expInfo, runtimeInfo=None,
originPath='C:\\Users\\mw24396\\Documents\\GitHub\\DANVA\\2_template demographics inside psychopy builder.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 after the window creation
# Setup the Window
win = visual.Window(
size=[1920, 1080], fullscr=True, screen=0,
winType='pyglet', allowGUI=False, allowStencil=False,
monitor='testMonitor', color=[-0.396,-0.396,-0.396], 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
# Setup eyetracking
ioDevice = ioConfig = ioSession = ioServer = eyetracker = None
# create a default keyboard (e.g. to check for escape)
defaultKeyboard = keyboard.Keyboard()
# Initialize components for Routine "readyMessage"
readyMessageClock = core.Clock()
Instructions = visual.TextStim(win=win, name='Instructions',
text="I am going to show you some people's faces and I want you to tell me how they feel. I want you to tell me if they are happy, sad, angry, or fearful (scared). Let's get started.\n(Esc will quit, laptops may require clicking quit button)\n\n\nPress any key to continue",
font='Arial',
pos=(0, 0), height=0.1, wrapWidth=None, ori=0,
color='white', colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=0.0);
starttest = keyboard.Keyboard()
mouse = event.Mouse(win=win)
x, y = [None, None]
mouse.mouseClock = core.Clock()
# This is a begin experiment comment in the code section of the readymessage section
errorList = []
skippedList = []
skippedErrors = 0
totalErrors = 0
happyHighIntensityErrors = 0
happyLowIntensityErrors = 0
sadHighIntensityErrors = 0
sadLowIntensityErrors = 0
angryHighIntensityErrors = 0
angryLowIntensityErrors = 0
fearfulHighIntensityErrors = 0
fearfulLowIntensityErrors = 0
happyErrors = 0
sadErrors = 0
angryErrors = 0
fearfulErrors = 0
lowIntensityErrors = 0
highIntensityErrors = 0
misattributedHappyToSad = 0
misattributedHappyToAngry = 0
misattributedHappyToFearful = 0
misattributedSadToHappy = 0
misattributedSadtoAngry = 0
misattributedSadToFearful = 0
misattributedAngryToHappy = 0
misattributedAngryToSad = 0
misattributedAngryToFearful = 0
misattributedFearfulToHappy = 0
misattributedFearfulToSad = 0
misattributedFearfulToAngry = 0
# This is to set the number of the trial for scoring the right data
thisTrialNumber = 0
# Initialize components for Routine "trial"
trialClock = core.Clock()
image = visual.ImageStim(
win=win,
name='image', units='height',
image='sin', mask=None,
ori=0, pos=(0, 0), size=(0.6936,0.4704) ,
color=[1,1,1], colorSpace='rgb', opacity=1,
flipHoriz=False, flipVert=False,
texRes=128, interpolate=True, depth=0.0)
slider = visual.Slider(win=win, name='slider',
startValue=None, size=(1.0, 0.1), pos=(0, -0.6), units=None,
labels=["HAPPY", "SAD", "ANGRY", "FEARFUL"], ticks=(1, 2, 3, 4), granularity=1,
style=['rating'], styleTweaks=[], opacity=1,
color='LightGray', fillColor='Red', borderColor='White', colorSpace='rgb',
font='HelveticaBold', labelHeight=0.05,
flip=False, depth=-1, readOnly=False)
next_button = visual.TextStim(win=win, name='next_button',
text='CONTINUE',
font='Arial',
pos=(.7, -0.6), height=0.1, wrapWidth=None, ori=0,
color='white', colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=-2.0);
mouse_2 = event.Mouse(win=win)
x, y = [None, None]
mouse_2.mouseClock = core.Clock()
# this is a begin experiment comment
# 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 "readyMessage"-------
continueRoutine = True
# update component parameters for each repeat
starttest.keys = []
starttest.rt = []
_starttest_allKeys = []
# setup some python lists for storing info about the mouse
gotValidClick = False # until a click is received
# This is a begin routine comment in the code section of the readymessage section
# keep track of which components have finished
readyMessageComponents = [Instructions, starttest, mouse]
for thisComponent in readyMessageComponents:
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")
readyMessageClock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1
# -------Run Routine "readyMessage"-------
while continueRoutine:
# get current time
t = readyMessageClock.getTime()
tThisFlip = win.getFutureFlipTime(clock=readyMessageClock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *Instructions* updates
if Instructions.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
Instructions.frameNStart = frameN # exact frame index
Instructions.tStart = t # local t and not account for scr refresh
Instructions.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(Instructions, 'tStartRefresh') # time at next scr refresh
Instructions.setAutoDraw(True)
# *starttest* updates
waitOnFlip = False
if starttest.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
starttest.frameNStart = frameN # exact frame index
starttest.tStart = t # local t and not account for scr refresh
starttest.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(starttest, 'tStartRefresh') # time at next scr refresh
starttest.status = STARTED
# keyboard checking is just starting
waitOnFlip = True
win.callOnFlip(starttest.clock.reset) # t=0 on next screen flip
win.callOnFlip(starttest.clearEvents, eventType='keyboard') # clear events on next screen flip
if starttest.status == STARTED and not waitOnFlip:
theseKeys = starttest.getKeys(keyList=None, waitRelease=False)
_starttest_allKeys.extend(theseKeys)
if len(_starttest_allKeys):
starttest.keys = _starttest_allKeys[-1].name # just the last key pressed
starttest.rt = _starttest_allKeys[-1].rt
# a response ends the routine
continueRoutine = False
# *mouse* updates
if mouse.status == NOT_STARTED and t >= 0.0-frameTolerance:
# keep track of start time/frame for later
mouse.frameNStart = frameN # exact frame index
mouse.tStart = t # local t and not account for scr refresh
mouse.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(mouse, 'tStartRefresh') # time at next scr refresh
mouse.status = STARTED
mouse.mouseClock.reset()
prevButtonState = mouse.getPressed() # if button is down already this ISN'T a new click
if mouse.status == STARTED: # only update if started and not finished!
buttons = mouse.getPressed()
if buttons != prevButtonState: # button state changed?
prevButtonState = buttons
if sum(buttons) > 0: # state changed to a new click
continueRoutine = 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 readyMessageComponents:
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 "readyMessage"-------
for thisComponent in readyMessageComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
thisExp.addData('Instructions.started', Instructions.tStartRefresh)
thisExp.addData('Instructions.stopped', Instructions.tStopRefresh)
# store data for thisExp (ExperimentHandler)
thisExp.addData('mouse.started', mouse.tStart)
thisExp.addData('mouse.stopped', mouse.tStop)
thisExp.nextEntry()
# this is an end routing comment in the readymessage
# the Routine "readyMessage" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# set up handler to look after randomisation of conditions etc
EmotionTests = data.TrialHandler(nReps=1, method='sequential',
extraInfo=expInfo, originPath=-1,
trialList=data.importConditions('facesBlock.csv'),
seed=None, name='EmotionTests')
thisExp.addLoop(EmotionTests) # add the loop to the experiment
thisEmotionTest = EmotionTests.trialList[0] # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb = thisEmotionTest.rgb)
if thisEmotionTest != None:
for paramName in thisEmotionTest:
exec('{} = thisEmotionTest[paramName]'.format(paramName))
for thisEmotionTest in EmotionTests:
currentLoop = EmotionTests
# abbreviate parameter names if possible (e.g. rgb = thisEmotionTest.rgb)
if thisEmotionTest != None:
for paramName in thisEmotionTest:
exec('{} = thisEmotionTest[paramName]'.format(paramName))
# ------Prepare to start Routine "trial"-------
continueRoutine = True
# update component parameters for each repeat
image.setImage(stimFile)
slider.reset()
# setup some python lists for storing info about the mouse_2
mouse_2.clicked_name = []
gotValidClick = False # until a click is received
# this is a begin routine comment
# keep track of which components have finished
trialComponents = [image, slider, next_button, mouse_2]
for thisComponent in trialComponents:
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")
trialClock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
frameN = -1
# -------Run Routine "trial"-------
while continueRoutine:
# get current time
t = trialClock.getTime()
tThisFlip = win.getFutureFlipTime(clock=trialClock)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *image* updates
if image.status == NOT_STARTED and tThisFlip >= .1-frameTolerance:
# keep track of start time/frame for later
image.frameNStart = frameN # exact frame index
image.tStart = t # local t and not account for scr refresh
image.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(image, 'tStartRefresh') # time at next scr refresh
image.setAutoDraw(True)
if image.status == STARTED:
# is it time to stop? (based on global clock, using actual start)
if tThisFlipGlobal > image.tStartRefresh + 2-frameTolerance:
# keep track of stop time/frame for later
image.tStop = t # not accounting for scr refresh
image.frameNStop = frameN # exact frame index
win.timeOnFlip(image, 'tStopRefresh') # time at next scr refresh
image.setAutoDraw(False)
# *slider* updates
if slider.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
slider.frameNStart = frameN # exact frame index
slider.tStart = t # local t and not account for scr refresh
slider.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(slider, 'tStartRefresh') # time at next scr refresh
slider.setAutoDraw(True)
# *next_button* updates
if next_button.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
next_button.frameNStart = frameN # exact frame index
next_button.tStart = t # local t and not account for scr refresh
next_button.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(next_button, 'tStartRefresh') # time at next scr refresh
next_button.setAutoDraw(True)
# *mouse_2* updates
if mouse_2.status == NOT_STARTED and t >= 0.0-frameTolerance:
# keep track of start time/frame for later
mouse_2.frameNStart = frameN # exact frame index
mouse_2.tStart = t # local t and not account for scr refresh
mouse_2.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(mouse_2, 'tStartRefresh') # time at next scr refresh
mouse_2.status = STARTED
mouse_2.mouseClock.reset()
prevButtonState = mouse_2.getPressed() # if button is down already this ISN'T a new click
if mouse_2.status == STARTED: # only update if started and not finished!
buttons = mouse_2.getPressed()
if buttons != prevButtonState: # button state changed?
prevButtonState = buttons
if sum(buttons) > 0: # state changed to a new click
# check if the mouse was inside our 'clickable' objects
gotValidClick = False
try:
iter(next_button)
clickableList = next_button
except:
clickableList = [next_button]
for obj in clickableList:
if obj.contains(mouse_2):
gotValidClick = True
mouse_2.clicked_name.append(obj.name)
if gotValidClick: # abort routine on response
continueRoutine = False
#this is an "each frame" comment
# 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 trialComponents:
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 "trial"-------
for thisComponent in trialComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
EmotionTests.addData('image.started', image.tStartRefresh)
EmotionTests.addData('image.stopped', image.tStopRefresh)
EmotionTests.addData('slider.response', slider.getRating())
EmotionTests.addData('slider.rt', slider.getRT())
EmotionTests.addData('slider.started', slider.tStartRefresh)
EmotionTests.addData('slider.stopped', slider.tStopRefresh)
EmotionTests.addData('next_button.started', next_button.tStartRefresh)
EmotionTests.addData('next_button.stopped', next_button.tStopRefresh)
# store data for EmotionTests (TrialHandler)
x, y = mouse_2.getPos()
buttons = mouse_2.getPressed()
if sum(buttons):
# check if the mouse was inside our 'clickable' objects
gotValidClick = False
try:
iter(next_button)
clickableList = next_button
except:
clickableList = [next_button]
for obj in clickableList:
if obj.contains(mouse_2):
gotValidClick = True
mouse_2.clicked_name.append(obj.name)
EmotionTests.addData('mouse_2.x', x)
EmotionTests.addData('mouse_2.y', y)
EmotionTests.addData('mouse_2.leftButton', buttons[0])
EmotionTests.addData('mouse_2.midButton', buttons[1])
EmotionTests.addData('mouse_2.rightButton', buttons[2])
if len(mouse_2.clicked_name):
EmotionTests.addData('mouse_2.clicked_name', mouse_2.clicked_name[0])
EmotionTests.addData('mouse_2.started', mouse_2.tStart)
EmotionTests.addData('mouse_2.stopped', mouse_2.tStop)
# this is an "end routine" comment in the trial section
if slider.rating == None:
errorList.append('Skipped')
if slider.getRating() != correctAnswer:
totalErrors = totalErrors + 1
if slider.getRating() == 0:
skippedErrors = skippedErrors + 1
errorList.append('Skipped')
elif correctAnswer == 1:
happyErrors = happyErrors + 1
errorList.append('Happy')
if intensity == 1:
happyLowIntensityErrors = happyLowIntensityErrors + 1
lowIntensityErrors = lowIntensityErrors + 1
else:
happyHighIntensityErrors = happyHighIntensityErrors + 1
highIntensityErrors = highIntensityErrors + 1
if slider.getRating() == 2:
misattributedHappyToSad = misattributedHappyToSad + 1
errorList.append('Sad')
elif slider.getRating() == 3:
misattributedHappyToAngry = misattributedHappyToAngry + 1
errorList.append('Angry')
else: #slider.getRation() == 4:
misattributedHappyToFearful = misattributedHappyToFearful + 1
errorList.append('Fearful')
elif correctAnswer == 2:
sadErrors = sadErrors + 1
if intensity == 1:
sadLowIntensityErrors = sadLowIntensityErrors + 1
lowIntensityErrors = lowIntensityErrors + 1
else:
sadHighIntensityErrors = sadHighIntensityErrors + 1
highIntensityErrors = highIntensityErrors + 1
if slider.getRating() == 1:
misattributedSadToHappy = misattributedSadToHappy + 1
errorList.append('Happy')
elif slider.getRating() == 3:
misattributedSadtoAngry = misattributedSadtoAngry + 1
errorList.append('Angry')
else:
misattributedSadToFearful = misattributedSadToFearful + 1
errorList.append('Fearful')
elif correctAnswer == 3:
angryErrors = angryErrors + 1
if intensity == 1:
angryLowIntensityErrors = angryLowIntensityErrors + 1
lowIntensityErrors = lowIntensityErrors + 1
else:
angryHighIntensityErrors = angryHighIntensityErrors + 1
highIntensityErrors = highIntensityErrors + 1
if slider.getRating() == 1:
misattributedAngryToHappy = misattributedAngryToHappy + 1
errorList.append('Happy')
elif slider.getRating() == 2:
misattributedAngryToSad = misattributedAngryToSad + 1
errorList.append('Sad')
else:
misattributedAngryToFearful = misattributedAngryToFearful + 1
errorList.append('Fearful')
elif correctAnswer == 4:
fearfulErrors = fearfulErrors + 1
if intensity == 1:
angryLowIntensityErrors = angryLowIntensityErrors + 1
lowIntensityErrors = lowIntensityErrors + 1
else:
angryHighIntensityErrors = angryHighIntensityErrors + 1
highIntensityErrors = highIntensityErrors + 1
if slider.getRating() == 1:
misattributedFearfulToHappy = misattributedFearfulToHappy + 1
errorList.append('Happy')
elif slider.getRating() == 2:
misattributedFearfulToSad = misattributedFearfulToSad + 1
errorList.append('sad')
else:
misattributedFearfulToAngry = misattributedFearfulToAngry + 1
errorList.append('Angry')
thisTrialNumber = thisTrialNumber + 1
# the Routine "trial" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
thisExp.nextEntry()
# completed 1 repeats of 'EmotionTests'
# this is an end experiment comment in the readymessage section
# "this is an end experiment comment
# 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', delim='auto')
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()