Pygame不会将图像拖到画布上

时间:2018-10-09 18:01:58

标签: python pygame blit

我在一个正在进行的小项目中为gui创建了一个图标,而pygame却不显示它。我在做什么错了?

import pygame
black = (0,0,0)
toolscanvas = pygame.Surface((700,120))

pygame.init()
gameDisplay = pygame.display.set_mode((0,0),pygame.FULLSCREEN)
gameDisplay.fill(black)
gameDisplay.convert()
clock = pygame.time.Clock()


class GuiHouse:
    def __init__(self):
        self.x = 0
        self.y = 20
        self.canvas = pygame.Surface((300,300))
        self.canvas.set_alpha(128)
        self.iconed = pygame.image.load("house_icon.png").convert_alpha()
        self.iconed = pygame.transform.scale(self.iconed, (60, 60))
    def display(self):
        global toolscanvas
        toolscanvas.fill((0,0,0))
        self.canvas.blit(self.iconed, (0, 0))
        toolscanvas.blit(self.canvas, (self.x, self.y))
        gameDisplay.blit(toolscanvas,(0,0))


guihouse = GuiHouse()
while True:
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                pygame.quit()
                quit()
    guihouse.display()
    pygame.display.update()
    clock.tick(120)

真实代码要长得多,如果它不起作用,请告诉我。 图标的外观如下所示:house_icon

1 个答案:

答案 0 :(得分:2)

有两个小错误

  1. 您忘记在pygame的主显示屏(gameDisplay.blit(toolscanvas, (0, 0)))上绘制 toolscanvas
  2. 通过Alfa通道读取的图像只有黑色像素。因此,您正在黑色背景上绘制黑色图片。在示例解决方案中,我添加了用白色填充图像画布,因此现在图像可见,但不美观。但我希望您能找到更好的解决方案:)

示例解决方案:

black = (0, 0, 0)
white = (255, 255, 255)
toolscanvas = pygame.Surface((700, 120))

pygame.init()
gameDisplay = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
gameDisplay.fill(black)
gameDisplay.convert()
clock = pygame.time.Clock()


class GuiHouse:
    def __init__(self):
        self.x = 0
        self.y = 20
        self.canvas = pygame.Surface((300, 300))
        self.canvas.set_alpha(128)
        self.canvas.fill(white)
        self.iconed = pygame.image.load("house_icon.png").convert_alpha()
        self.iconed = pygame.transform.scale(self.iconed, (60, 60))

    def display(self):
        global toolscanvas
        toolscanvas.fill((0, 0, 0))
        self.canvas.blit(self.iconed, (0, 0))
        toolscanvas.blit(self.canvas, (self.x, self.y))
        gameDisplay.blit(toolscanvas, (0, 0))

guihouse = GuiHouse()
while True:
    guihouse.display()
    pygame.display.update()
    clock.tick(120)