display a message to user if makes error, and make it disapear only if he fix it

I’m trying with this piece of code make a text appear when the condition is respected and then make it disappear, without refreshing all the page

it’s like a small warning that appears when the player does something wrong and then disappear if he correct it.

for i in range (len(grid)): 
          if 2 not in grid[i] :  
            if grid[i] == grid[i -1]:
              display = True
              if display== True:
              #add a msg text    
                countText = myfont.render( "check the row again!", 1, (255, 0, 0))
                countRect = countText.get_rect()
                countRect.y, countRect.centerx = 10, 450
                SCREEN.set_clip(countRect)        # Allow updates only to area in countRect
                SCREEN.blit(background, (0,0))      # bg_img will only be drawn within countRect
                SCREEN.blit(countText, countRect)
                pygame.display.flip()
            else: 
              pass
      
              #countText = myfont.render('emptyagain', False, (0, 0, 0))
              #SCREEN.blit(background,(410,10))
              #SCREEN.fill(SNOW_COLOR)


thank you 🙂

Answer

If you want the text to be persistent, you need to draw the message in the application loop.

Add a variable displayWarning in the global namespace. Reset the variable before the loop but set it True inside the loop:

displayWarning = Fasle
global displayWarning # just if this code is in a function

displayWarning = False
for i in range (len(grid)): 
    if 2 not in grid[i] :  
        if grid[i] == grid[i -1]:
            displayWarning = True

Draw the text in the application loop

# application loop
while run: 
    # [...]

    SCREEN.blit(background, (0,0))

    # [...]

    if displayWarning:
        countText = myfont.render( "check the row again!", 1, (255, 0, 0))
        countRect = countText.get_rect()
        countRect.y, countRect.centerx = 10, 450
        SCREEN.blit(countText, countRect)
        
    # [...]

    pygame.display.flip()