Hey guys I am trying to change the color of the text for the slider/click line response option but I can not find it. I have tried the following in the coding option:
color='black'
But no success, help!
Hey guys I am trying to change the color of the text for the slider/click line response option but I can not find it. I have tried the following in the coding option:
color='black'
But no success, help!
In order to set the color property of an object, you need to refer to that object, otherwise you’re just creating a variable called color
which isn’t linked to anything! If we were to call your slider mySlider
, the code would look like this:
mySlider.color = 'black'
Thanks for the help. I get an odd error now, here’s what the error says:
## Running: C:\Users\micha\Desktop\school\RESEARCH_lastrun.py ##
143.2702 EXP Imported chooseBlock.csv as conditions, 1 conditions, 2 params
File "C:\Users\micha\Desktop\school\RESEARCH\blockedTrials_lastrun.py",
line 106
rating = visual.RatingScale(win=win, name='rating', mySlider.color = 'black')
^
SyntaxError: keyword can't be an expression
##### Experiment ended. #####
Here’s the total code around line 106:
# 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)
rating = visual.RatingScale(win=win, name='rating', mySlider.color = 'black')
Here’s the total code for everything
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This experiment was created using PsychoPy3 Experiment Builder (v2020.1.3),
on October 20, 2020, at 12:35
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.3'
expName = 'blockedTrials' # 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 + 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\\micha\\Desktop\\school\\RESEARCH\\VA\\2_PSYCHOPVAII\\blockedTrials_lastrun.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=[1920, 1080], fullscr=True, screen=4,
winType='pyglet', allowGUI=True, allowStencil=False,
monitor='testMonitor', color=[0.710,0.710,0.710], 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 "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)\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()
# 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)
rating = visual.RatingScale(win=win, name='rating', mySlider.color = 'black')
# 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
# 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()
# 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
blocks = data.TrialHandler(nReps=1, method='random',
extraInfo=expInfo, originPath=-1,
trialList=data.importConditions('chooseBlock.csv'),
seed=None, name='blocks')
thisExp.addLoop(blocks) # add the loop to the experiment
thisBlock = blocks.trialList[0] # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb = thisBlock.rgb)
if thisBlock != None:
for paramName in thisBlock:
exec('{} = thisBlock[paramName]'.format(paramName))
for thisBlock in blocks:
currentLoop = blocks
# abbreviate parameter names if possible (e.g. rgb = thisBlock.rgb)
if thisBlock != None:
for paramName in thisBlock:
exec('{} = thisBlock[paramName]'.format(paramName))
# set up handler to look after randomisation of conditions etc
trials = data.TrialHandler(nReps=1, method='sequential',
extraInfo=expInfo, originPath=-1,
trialList=data.importConditions(condsFile),
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 "trial"-------
continueRoutine = True
# update component parameters for each repeat
image.setImage(stimFile)
rating.reset()
# keep track of which components have finished
trialComponents = [image, rating]
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 >= 0-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 + 1.9-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)
# *rating* updates
if rating.status == NOT_STARTED and t >= 0.0-frameTolerance:
# keep track of start time/frame for later
rating.frameNStart = frameN # exact frame index
rating.tStart = t # local t and not account for scr refresh
rating.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(rating, 'tStartRefresh') # time at next scr refresh
rating.setAutoDraw(True)
continueRoutine &= rating.noResponse # a response ends the trial
# 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)
trials.addData('image.started', image.tStartRefresh)
trials.addData('image.stopped', image.tStopRefresh)
# store data for trials (TrialHandler)
trials.addData('rating.response', rating.getRating())
trials.addData('rating.rt', rating.getRT())
trials.addData('rating.started', rating.tStart)
trials.addData('rating.stopped', rating.tStop)
# the Routine "trial" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
thisExp.nextEntry()
# completed 1 repeats of 'trials'
# completed 1 repeats of 'blocks'
# 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()
Oh, I see, you meant when initialising the object. My mistake!
So the slider is an instance
of a class
called RatingScale
- when you create it, you pass the class a load of information describing what kind of RatingScale
you want to create. With these you supply labels, in this case color
, and the class
will have methods for storing that information in the property. Once the instance
has been created, it will have the name you gave it, in this case rating
and you can then change its color by using rating.color
. That’s what I thought you were trying to do.
To change the color when creating it, the label you need to use for RatingScale
is textColor
. However, RatingScale
is no longer under active support so I would recommend switching to the much more recent Slider
component, which can do all the same things as Rating Scale
and more! For that one you would use color
.