首页 > 解决方案 > Pygame - 无法将图像绘制到屏幕:TypeError:draw()缺少1个必需的位置参数:'surface'

问题描述

我想在屏幕上画一个框,但是当我调用该函数时,它说我缺少“表面”的参数

如下代码所示,该函数位于一个类中。该函数包含两个参数:“self”和“surface”,我传递变量“screen”代替“surface”,这样我就可以绘制框了:

import pygame
import time
pygame.init()
(width, height) = (600, 400)
bg_colour = (100, 20, 156)

class infoBox(object):
    def __init__(self, surface):
        self.box = pygame.draw.rect(surface, (255,255,255),(0,400,400,100),2)

    def draw(self, surface):
        surface.blit(self.box)

screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("battle EduGame")

clock = pygame.time.Clock()

pygame.display.flip()

gameRun = True


while gameRun:
    event = pygame.event.poll()
    if event.type == pygame.QUIT: #if the "x" is pressed
       pygame.quit() #quit game
       gameRun = False #break the loop.
       quit()

    screen.fill(bg_colour)

    infoBox.draw(screen)


    pygame.display.update()


    clock.tick(60)

我在以前的代码中做了完全一样的事情,但是它选择不在这里工作。

标签: pythonpygame

解决方案


注意你的调用技巧:

class infoBox(object):

    def draw(self, surface):
        surface.blit(self.box)
...

infoBox.draw(screen)

draw是一个实例方法,但您已将其作为类方法调用。因此,您只有一个论点,screen。您还没有提供所需的self实例......将立即需要。

您需要创建对象并使用来调用例程,例如

game_box = InfoBox(screen)
...
game_box.draw(screen)

推荐阅读