Synchronizing Spacebar Press and Release

Hello everyone, I am struggling with an experiment I’m trying to implement. I should say that I’ve recently started using PsychoPy, yet I decided to use the Coder instead of the Builder. What I’m trying to do is create a trial with the following sequence: presentation of an image, which by default is shown for 6 seconds. The participant can press the spacebar to proceed starting from 3 seconds onward; if they press the spacebar to proceed before 3 seconds, the trial cannot proceed. Also, if the spacebar is not pressed within the 6 seconds the image is displayed, the trial does not advance until the participant presses the spacebar. Once the spacebar is pressed, it must be held down. When the spacebar is pressed, the image disappears, and a question appears on the screen. When the spacebar is released, this question disappears, and a new routine appears. I’ve tried to set up the code as shown below, but it seems there are some errors; the timing and sequence between the routines don’t appear to be correct.
Could you please help me with this?

#Selezione casuale immagine
spacebar_pressed = False 
selectedImagePath = random.choice(image_paths) 
picture = visual.ImageStim(win, selectedImagePath)
picture.draw()
win.flip()
core.wait(6)
start_time = core.getTime()
pressed = False  # Inizializza la variabile per registrare se la barra spaziatrice è stata premuta

#loop di spacebar
while True:
    now = core.getTime()
    if now - start_time >= 3 and 'space' in event.getKeys():
        pressed = True
        break
    if now - start_time >= 6:
        break

if not pressed:
    event.waitKeys(keyList=["space"], maxWait=6 - (now - start_time))

############################################# 4°Window (Task1)
key_released = False
task_1 = visual.TextStim(win, text="Questa immagine mi è piaciuta", color='black', height=50 )
task_1.draw()
win.flip()
while True:
    response_event=event.getKeys(['space'])
    if response_event:
        key_released = True
        break

# creazione slider
key_released = True
sliderValue_1 = 0  # valore predefinito

Why have you decided to use Coder?

I’ve tried to set up the code as shown below, but it seems there are some errors; the timing and sequence between the routines don’t appear to be correct.

Help people to help you by being specific about the errors and unexpected behaviour.

I do not receive any error messages from Psychopy. The issue appears to be a lack of synchronization between the various trial routines. For instance, when the spacebar is pressed, the image should disappear and the task 1 should appear immediately, but this does not happen.