为什么在 PyGame 中什么都没有绘制?

问题描述 投票:0回答:2

我已经使用 pygame 在 python 中开始了一个新项目,对于背景,我希望下半部分填充灰色,顶部填充黑色。我以前在项目中使用过矩形绘图,但由于某种原因它似乎被破坏了?我不知道我做错了什么。最奇怪的是我每次运行程序的结果都不一样。有时只有黑屏,有时灰色矩形会覆盖部分屏幕,但不会覆盖屏幕的一半。

import pygame, sys
from pygame.locals import *
pygame.init()

DISPLAY=pygame.display.set_mode((800,800))
pygame.display.set_caption("thing")
pygame.draw.rect(DISPLAY, (200,200,200), pygame.Rect(0,400,800,400))

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
python pygame rectangles
2个回答
4
投票

您需要更新显示。 你实际上是在一个

Surface
对象上画画。如果您在与 PyGame 显示相关联的 Surface 上绘制,这不会立即显示在显示中。当使用
pygame.display.update()
pygame.display.flip()
更新显示时,更改变得可见。

pygame.display.flip()

这将更新整个显示的内容。

虽然

pygame.display.flip()
会更新整个显示的内容,
pygame.display.update()
只允许更新屏幕的一部分,而不是整个区域。
pygame.display.update()
pygame.display.flip()
的优化版本,适用于软件显示,但不适用于硬件加速显示。

典型的 PyGame 应用程序循环必须:

import pygame
from pygame.locals import *
pygame.init()

DISPLAY = pygame.display.set_mode((800,800))
pygame.display.set_caption("thing")
clock = pygame.time.Clock()

run = True
while run:
    # handle events
    for event in pygame.event.get():
        if event.type == QUIT:
            run = False

    # clear display
    DISPLAY.fill(0)

    # draw scene
    pygame.draw.rect(DISPLAY, (200,200,200), pygame.Rect(0,400,800,400))

    # update display
    pygame.display.flip()

    # limit frames per second
    clock.tick(60)

pygame.quit()
exit()

repl.it/@Rabbid76/PyGame-MinimalApplicationLoop 另见Event and application loop


0
投票

只需将您的代码更改为:

import pygame, sys
from pygame.locals import *
pygame.init()

DISPLAY=pygame.display.set_mode((800,800))
pygame.display.set_caption("thing")
pygame.draw.rect(DISPLAY, (200,200,200), pygame.Rect(0,400,800,400))
pygame.display.flip() #Refreshing screen

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

应该有帮助

© www.soinside.com 2019 - 2024. All rights reserved.