Sofiane M'barki Sofiane M'barki - 14 days ago 5
Python Question

Blinking rectangle white pygame with specific frequency

I'm student at university and I have a specific question.

Presently I display a white rectangle in center of a window with pygame above a black background. But presently I would like to blinking my white rectangle at a specific frequency, and it's why a I need help.

Presently I implement that:

import pygame, sys
from pygame.locals import *

def main():
pygame.init()

fenetre = pygame.display.set_mode((500,400),0,32)

black=(0,0,0)
white=(255,255,255)

fenetre.fill(black)

pygame.draw.rect(fenetre, white,(200,150,100,50))


while True:
for event in pygame.event.get():
if event.type==QUIT:
pygame.quit()
sys.exit()
pygame.display.update()

main()


enter image description here

Thanks for your help community.

Answer

I made some edits to your code to fit your needs and tested it.

The Code

import pygame
import sys
import time
from pygame.locals import *

pygame.init()

fenetre = pygame.display.set_mode((500, 400), 0, 32)
black = (0, 0, 0)
white = (255, 255, 255)
clock = pygame.time.Clock()

frequency = 1


def main():

    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()

        pygame.draw.rect(fenetre, black, (200, 150, 100, 50))
        pygame.display.update()
        time.sleep(frequency)
        pygame.draw.rect(fenetre, white, (200, 150, 100, 50))
        pygame.display.update()
        time.sleep(frequency)
        clock.tick(30)


main()

The result should be the rect appearing each 1 sec

Comments