I’m very new to Psychopy with no previous experience in coding.
I’m trying to create an experiment with 8 blocks - 4 asking one question (ID blocks) and 4 asking another (Likert blocks), alternating between the two questions for each successive block.
Each block needs to contain 10 images randomly selected from a list of 40, but it should exclude images already selected by previous blocks of the same type (i.e. the 10 images used in the first ID block shouldn’t be selected in the second ID block).
I can’t figure out how to display the images with the logic I want.
With the help of AI, I tried using a code component and writing this in the ‘Begin Experiment’ tab:
import pandas as pd
import random
# Read the Excel file
image_list = pd.read_excel('images.xlsx')['image_files'].tolist()
# Ensure the image list is of expected length
if len(image_list) != 40:
raise ValueError("The image list must contain exactly 40 images.")
# Create 4 blocks of 10 unique images each
blocks = []
remaining_images = image_list.copy()
for i in range(4):
block_images = random.sample(remaining_images, 10)
blocks.append(block_images)
remaining_images = [img for img in remaining_images if img not in block_images]
# Flatten the blocks list to iterate through images in sequence
all_images = sum(blocks, [])
and this in the ‘Begin Routine’ tab:
# Determine the trial number
trial_num = self.thisN if self.thisN is not None else 0 # Get the current trial number
# Set the current image
if trial_num < len(all_images):
current_image = all_images[trial_num]
else:
current_image = None # Safety check
and inserting an image component referring to $current_image
However I’m getting this error:
image.setImage(current_image)
UnboundLocalError: local variable 'current_image' referenced before assignment
################ Experiment ended with exit code 1 [pid:22613] #################
Can anyone help me solve this? I’ve been trying to get AI to help me with this but I think it’s only creating a bigger mess.
Thanks everyone.