【问题标题】:Why is nothing drawn in PyGame at all?为什么 PyGame 中根本没有绘制任何内容?
【发布时间】:2021-03-14 18:14:00
【问题描述】:

我已经使用 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


【解决方案1】:

您需要更新显示。 您实际上是在 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

【讨论】:

  • @MinerBat 这似乎是与您的系统缺乏清除和刷新显示有关的副作用。这没有合乎逻辑的理由。与系统的内部交互也与事件处理有关。见pygame.event.pump()
【解决方案2】:

只需将代码更改为:

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

应该有帮助

【讨论】:

    猜你喜欢
    • 2022-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多