Pygame无法获取背景图片?

时间:2020-01-23 18:29:45

标签: python class background pygame

我得到的只是一个黑屏。 不知道我是否在目录中找不到该图像,或者如果我没有正确调用某些图像,则不知道...但是它没有给我一个错误,所以我不确定该怎么做。

import pygame
# Intialize the pygame
pygame.init()

# Create the screen 
screen = pygame.display.set_mode((300, 180))

#Title and Icon
pygame.display.set_caption("Fighting Game")

# Add's logo to the window 
# icon = pygame.image.load('')
# pygame.display.set_icon(icon)

#  Game Loop
running = True
while running:
    # screen.fill((0, 0, 0))
    # screen.blit(BackGround.image, BackGround.rect)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False


class Background(pygame.sprite.Sprite):
    def __init__(self, image_file, location):
        pygame.sprite.Sprite.__init__(self)  #call Sprite initializer
        self.image = pygame.image.load("images/image.png")
        self.rect = self.image.get_rect(300,180)
        self.rect.left, self.rect.top = location

BackGround = Background('image.png', [0,0])

screen.fill((0, 0, 0))
screen.blit(BackGround.image, BackGround.rect)

1 个答案:

答案 0 :(得分:4)

您必须在主应用程序循环中blit镜像,并且必须通过pygame.display.flip更新显示。

此外,没有必要将任何参数传递给self.image.get_rect()。无论如何,get_rect()的参数必须是关键字参数。 您可以通过关键字参数topleft设置位置。

class Background(pygame.sprite.Sprite):
    def __init__(self, image_file, location):
        pygame.sprite.Sprite.__init__(self)  #call Sprite initializer
        self.image = pygame.image.load("images/image.png")
        self.rect = self.image.get_rect(topleft = location)

BackGround = Background('image.png', [0,0])

#  Game Loop
running = True
while running:
    # screen.fill((0, 0, 0))
    # screen.blit(BackGround.image, BackGround.rect)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    #screen.fill((0, 0, 0)) # unnecessary because of the background image
    screen.blit(BackGround.image, BackGround.rect)
    pygame.display.flip()

请注意,主应用程序循环必须:

  • 处理事件
  • 清除显示内容或使背景图像变白
  • 绘制场景
  • 更新显示