简体   繁体   English

pygame屏幕无法显示

[英]pygame screen failing to display

I have the following code in Python 3 (and pygame), but the white surface fails to display and I don't understand why. 我在Python 3(和pygame)中有以下代码,但白色表面无法显示,我不明白为什么。 Has it got something to do with where it has been placed? 它与它的位置有关吗? I tried de-indenting, but that didn't work either? 我试过去缩进,但这也不起作用? The code is as below: 代码如下:

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

screen=pygame.display.set_mode((800,600))


# Variable to keep our main loop running
running = True

# Our main loop!
while running:
    # for loop through the event queue
    for event in pygame.event.get():
        # Check for KEYDOWN event; KEYDOWN is a constant defined in pygame.locals, which we imported earlier
        if event.type == KEYDOWN:
            # If the Esc key has been pressed set running to false to exit the main loop
            if event.key == K_ESCAPE:
                running = False
            # Check for QUIT event; if QUIT, set running to false
            elif event.type == QUIT:
                running = False

            # Create the surface and pass in a tuple with its length and width
            surf = pygame.Surface((50, 50))
            # Give the surface a color to differentiate it from the background
            surf.fill((255, 255, 255))
            rect = surf.get_rect()

            screen.blit(surf, (400, 300))
            pygame.display.flip()

So it does appear that your indentation is wrong. 所以看来你的缩进是错误的。

You need to define the surface and update the screen etc. outside of the event loop. 您需要在事件循环之外定义曲面并更新屏幕等。

At the very least you must move the screen.blit(surf, (400, 300)) and pygame.display.flip() outside of the event loop. 至少你必须在事件循环之外移动screen.blit(surf, (400, 300))pygame.display.flip()

This is it fixed: 这是固定的:

# Our main loop!
while running:
    # for loop through the event queue
    for event in pygame.event.get():
        # Check for KEYDOWN event; KEYDOWN is a constant defined in pygame.locals, which we imported earlier
        if event.type == KEYDOWN:
            # If the Esc key has been pressed set running to false to exit the main loop
            if event.key == K_ESCAPE:
                running = False
            # Check for QUIT event; if QUIT, set running to false
            elif event.type == QUIT:
                running = False

    # Create the surface and pass in a tuple with its length and width
    surf = pygame.Surface((50, 50))
    # Give the surface a color to differentiate it from the background
    surf.fill((255, 255, 255))
    rect = surf.get_rect()

    screen.blit(surf, (400, 300))
    pygame.display.flip()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM