Continually draw() an imageStim ONLY while a key is being pressed down

Hello all,
I would like to find a way for an image to be continuously displayed on the screen while a key is being pressed down, and then disappear when the key is not being pressed, and this should be accomplished on the same routine as many times as the key is pressed.

I am using the keyboard class. So far, I have successfully made the image appear when the key is pressed, but it does not disappear when the key is not being pressed. It just stays forever.

Heres what I have in a code block on the routine:

(in before/begin experiment)

from psychopy.hardware import keyboard
from PIL import Image
from psychopy import core, event, visual

# the four images i want to be displayed based on keypresses
red = visual.ImageStim(win, image='redsquaresized.png')
green = visual.ImageStim(win, image='greensquaresized.png')
blue = visual.ImageStim(win, image='bluesquaresized.png')
yellow = visual.ImageStim(win, image='yellowsquaresized.png')

(in begin routine)

kb = keyboard.Keyboard()

(in each frame)

keys = kb.getKeys(['left', 'down', 'right', 'up'], waitRelease = False, clear = False)

for thisKey in keys:
    if thisKey == 'left':
        red.draw()
    elif thisKey == 'down':
        green.draw()
    elif thisKey == 'right':
        blue.draw()
    else:
        yellow.draw()

This works, the only issue being the images are permanently displayed after the key is pressed and do not disappear.
Thank you!

That is the issue - keypresses aren’t removed from the list, so once pressed, they are always detected in your code. However the solution isn’t simply to set that to True though - then your stimuli would only flash up briefly, as they will immediately get removed from the list.

The solution is to retain all the keypresses but check whether each one has a duration - if the duration is None, then the key hasn’t been released yet. If there is a duration, then the key must have been released. So change your code to:

for thisKey in keys:
    if thisKey == 'left' and thisKey.duration is None:
        red.draw()
    # etc etc 

PS you shouldn’t need any of those imports - Builder does all of those imports itself (except for PIL.Image - not sure why you would need explicit access to that).