我试图在 Pygame 中绘制一个矩形,但颜色闪烁......为什么? [英] I tried to draw a rectangle in Pygame but the colour is flickering...why?

查看:90
本文介绍了我试图在 Pygame 中绘制一个矩形,但颜色闪烁......为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我再次尝试 Pygame(仍然是初学者),我尝试绘制一个矩形,但颜色只是闪烁.(橙色表面的绿松石)为什么会发生这种情况?

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?

这是代码片段:

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()

谢谢大家:)

推荐答案

pygame.display.update(或者 pygame.display.flip) 函数应该每帧只调用一次(while 循环的迭代)) 在代码的绘图部分的末尾.

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.

只需删除第一个 pygame.display.update() 调用,程序就会正常运行.

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

关于代码的一些注意事项:定义常量(颜色)并在 while 循环之外创建屏幕(这与闪烁无关,但在 while 循环中执行此操作没有意义).另外,最好不要使用 star 导入(只有 from pygame.locals import * 是可以的如果它是唯一的明星导入).并使用时钟限制帧率.

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.

这篇关于我试图在 Pygame 中绘制一个矩形,但颜色闪烁......为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆