I tried to draw a rectangle in Pygame but the colour is flickering…why?

柔情痞子 提交于 2021-01-27 06:27:08

问题


So, I'm trying Pygame again (still a beginner), I tried to draw a rectangle, but the colour just flickers. (turquoise on orange surface) Why does this happen?

Here's the snippet of code:

from pygame import *
from sys import *

while True:
    init()

    for events in event.get():
        if events.type == QUIT:
            quit()
            exit()

    SCREENWIDTH = 900
    SCREENHEIGHT = 600
    SCREENSIZE = [SCREENWIDTH, SCREENHEIGHT]
    SCREEN = display.set_mode(SCREENSIZE)
    bg_col = [255, 123, 67]
    s1_col = (0, 255, 188)
    SCREEN.fill(bg_col)
    display.update()
    draw.rect(SCREEN, s1_col,(50, 25, 550, 565), 1) #problem area?
    display.update()

Thanks everyone :)


回答1:


The pygame.display.update (or alternatively pygame.display.flip) function should be called only once per frame (iteration of the while loop) at the end of the drawing section of the code.

Just remove the first pygame.display.update() call and the program will work correctly.


Some notes about the code: Define your constants (the colors) and create the screen outside of the while loop (that's unrelated to the flickering but it makes no sense to do this in the while loop). Also, better don't use star imports (only from pygame.locals import * is okay if it's the only star import). And use a clock to limit the frame rate.

import sys

import pygame
from pygame.locals import *


pygame.init()
# Use uppercase for constants and lowercase for variables (see PEP 8).
SCREENWIDTH = 900
SCREENHEIGHT = 600
SCREENSIZE = [SCREENWIDTH, SCREENHEIGHT]
screen = pygame.display.set_mode(SCREENSIZE)
clock = pygame.time.Clock()  # A clock object to limit the frame rate.
BG_COL = [255, 123, 67]
S1_COL = (0, 255, 188)

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

    screen.fill(BG_COL)
    pygame.draw.rect(screen, S1_COL, (50, 25, 550, 565), 1)
    pygame.display.update()
    clock.tick(60)  # Limits the frame rate to 60 FPS.


来源:https://stackoverflow.com/questions/53459007/i-tried-to-draw-a-rectangle-in-pygame-but-the-colour-is-flickering-why

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!