【问题标题】:pygame screen failing to displaypygame 屏幕无法显示
【发布时间】:2017-02-16 23:42:28
【问题描述】:

我在 Python 3(和 pygame)中有以下代码,但白色表面无法显示,我不明白为什么。它与放置的位置有关吗?我试过去缩进,但这也没用?代码如下:

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

【问题讨论】:

  • 你收到错误了吗?
  • “我试过去缩进,但也没用?” - 是的,不要那样做。随机缩进和消除代码对您没有帮助。
  • leaf - 您的评论也不是很有帮助。我的意思是取消缩进与表面绘图有关的代码。特里斯坦——不,没有错误。只是一个空白的黑屏
  • @pythoncarrot 但是你的窗口没有显示的全部原因是因为你的缩进。
  • 不正确。该程序完美运行。 (我可能将它错误地粘贴到stackoverflow,因为它弄乱了我的缩进)。只是当我添加表面位时,它不会绘制。注意上面的编辑 - 当这样使用时 - 会显示黑屏,但不是所需的表面。

标签: python pygame surface


【解决方案1】:

看来你的缩进是错误的。

您需要在事件循环之外定义表面并更新屏幕等。

至少您必须将screen.blit(surf, (400, 300))pygame.display.flip() 移到事件循环之外。

这是固定的:

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

【讨论】:

    猜你喜欢
    • 2018-05-18
    • 2020-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-18
    • 2015-09-05
    相关资源
    最近更新 更多