Search code examples
pythonpsychopy

how to print words in a different color from a list and then show it on a window in python?


How to add color to each word in a list in python and then print it into a window?

My code is this:

cognitivo = ["Plan","Organize","Help","liquidate","solvency","Prioritize","work","business","achievements","Control"]
for stimulus in cognitivo:
    mens = visual.TextStim(win, text=stimulus)
    mens.draw()
    win.flip()
    #core.wait(1.0) 

just copy the list and as it is printed with the for loop, not to copy all the code I did...Only prints in a color and what I want is that each word in a specific color...Please, can someone help me? Thanks.


Solution

  • To make things easier, what you probably want to do is create a dictionary for each trial that holds all trial-related info together in one object (e.g. the text and colour for a trial). That makes it very easy to loop through a list of such dictionaries and easily access the trial values. Look into the PsychoPy TrialHandler class, which will do all of this and more (including saving data).

    But just to fit within your simple code snippet, try this:

    cognitivo = ['Plan', 'Organize', 'Help', 'liquidate', 'solvency', 'Prioritize', 'work', 'business', 'achievements', 'Control']
    # create some corresponding colours:
    colors = ['red', 'green', 'yellow', 'blue', 'black'] * 2
    
    # initialise the text stimulus just once:
    mens = visual.TextStim(win, text = 'XXXXXX')
    
    # loop through the stimuli:
    for stimulus in cognitivo:
        # update the stimulus:
        mens.text = stimulus
        mens.color = colors.pop()
    
        # display for 1 second at 60 Hz:
        for frame in range(60)
            mens.draw()
            win.flip()
    

    Note that in general you shouldn't keep re-creating stimuli. Generally, just initialise it once, and then update its attributes. Creating a stimulus usually takes much longer than updating an existing one.