psychopy.org | Reference | Downloads | Github

Move back and forth from trials to trials with keyboard?


#1

In the following code, for instance, I tried to use the variable “page” as an index to pick up elements in a random list. But I got the “index out of range” error even I had tried to limit the range of “page”. It appears the variable “page” can still exceed -4 and 3.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from psychopy import visual, core, event
import random

win = visual.Window(fullscr = False, size = (1000,600),
                    color = (-1.0,-1.0,-1.0), units = 'norm', monitor = 'testMonitor')


def page_limit(page):
    if page>3:
        page=0
    elif page<0:
        page=3
    else: 
        pass
        
def participants(win):
    sequence=random.sample(range(1,5),4)
    page=0
    while True:
        page_limit(page)
        print(page)
        image=visual.ImageStim(win, image = ('images/'+str(sequence[page])+'.bmp'),size=(0.5,0.95),pos=(-0.55,0.35))
        image.draw()
        win.flip()
        k_4 = event.waitKeys(keyList=['a','d','s'],timeStamped=False)
        if k_4[0]=='a':
            page=page-1
        elif k_4[0]=='d':
            page=page+1
        else:
            win.close()
            core.quit()
                
participants(win)

#2

The problem with this code is with your page_limit function, it does not return the page variable, so the page is only changed within the function locally. Try the following:

def page_limit(page):
    if page>3:
        page=0
    elif page<0:
        page=3
    return page  # return the value of page whether or not it has been reset

...

def participants(win):
    sequence=random.sample(range(1,5),4)
    page=0
    while True:
        page = page_limit(page)  # redefine page using your value from page_limit
...

#3

Thanks, that really works out.