I ocassionally get the error 'Python.exe has stopped responding'. More details below

I am running an experiment where people see a stimulus for at least 60 seconds. After the 60s are over, they can exit the screen by pressing SPACE any time they want to (I have put an upper bound at 300s). Only 3 key inputs are legal, ‘left’, ‘right’, and ‘space’.

However, within the first 60s itself, I get a popup error: ‘Python.exe has stopped responding.’ I have updated Psychopy to the latest version (v2023.2.2), and I am using a Windows 10 system (however, the same error occurs on Windows 11, too). The rub is that this happens only occasionally. It also happens when I do not have any other program running, so RAM is not an issue. I suspect it is because I am running 2 loops but I cannot figure out how else I can code this or why it only happens sometimes.

Reproducible code:

from psychopy.visual import TextStim, ImageStim, Slider, RatingScale, ShapeStim
from psychopy import core, visual

win = visual.Window((800, 650))
kb = keyboard.Keyboard()
trial = [1, 2, 3, 4, 5, 6, 7, 8]
trial_start = core.getTime()

#screen details
def imagine(screen = 1, trial = trial, num = 0):
    if screen == 1:
        TextStim(win, text = "first screen").draw()
        win.flip()
    else:
        TextStim(win, text = "second screen").draw()
        win.flip()    
    return
    
'Imgine screen'
i = 1
imagine(screen=1, trial = trial, num = i + 1)
trial_onset = core.getTime() - trial_start    
delib_keys, delib_rt = [], []
kb.clock.reset()
keys = kb.getKeys(['left', 'right', 'space'])

while kb.clock.getTime() < 300:
    
    if keys:
        for key in keys:
            delib_keys.append(key.name)
            delib_rt.append(key.rt)
            
        if (kb.clock.getTime() > 60):
            imagine(screen = 2, trial = trial, num = i + 1)                
            if ('space' in keys): 
                break  

print(delib_keys, delib_rt)


win.close()
core.quit()

The error looks like this:
image

Any fixes?

Revati