为什么我的代码在pygame上运行程序时不显示我的图像?

2024-05-16 10:41:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用我导入到Pycharm中的Pygame

对于我的代码,我试图显示文件中的图像,以便在运行程序时加载到程序中,但它不起作用。该图像与我的python代码位于同一个文件中。当我运行它时,我看到的只是一个黑屏

图像的文件路径是正确的,因为当我将鼠标悬停在png文件上时,它显示了图像的预览

这是我的密码:


import pygame, sys

pygame.init()
screen = pygame.display.set_mode((1275, 775))

bg_surface = pygame.image.load("C:/Users/DavinaXXX/Documents/Python/Testing/Background.png")

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

screen.blit(bg_surface, (0, 0))


Tags: 文件代码图像路径程序eventpngsys
1条回答
网友
1楼 · 发布于 2024-05-16 10:41:30

你让它起作用了吗

在对屏幕进行更改之后,当调用pygame.display.flip()pygame.display.update()时,它们都会被写入或“刷新”到显示中(从更新队列)。您没有此调用,因此无法在窗口中看到blit更改

pygame.quit()也有一个问题,blit()需要缩进到while循环中,但这可能只是写问题时的粘贴问题

import pygame, sys

pygame.init()
screen = pygame.display.set_mode((1275, 775))

bg_surface = pygame.image.load("C:/Users/DavinaXXX/Documents/Python/Testing/Background.png")

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


    screen.blit(bg_surface, (0, 0))         # <<  HERE (indent into while)
    pygame.display.flip()                   # <<  AND HERE (added)

相关问题 更多 >