What does this error mean: TypeError: argument 1 m

2019-09-12 10:41发布

问题:

Here is my code, it is really simple:

bif="C:\\Users\\Andrew\\Pictures\\pygame pictures\\Background(black big).png"
import pygame, sys
from pygame.locals import *

pygame.init()

screen=pygame.display.set_mode((1000,1000),0,32)
background=pygame.image.load(bif).convert()
line=pygame.draw.line(background, (255,255,255), (30,31), (20,31))
while True:

    mousex, mousey = pygame.mouse.get_pos()
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
    screen.blit(background, (0,0))
    screen.blit(line,(mousex,mousey))
    pygame.display.update()

The goal of this is to have the line follow my mouse on the screen. However, whenever I try to run the program I get the error :

TypeError: argument 1 must be pygame.Surface, not pygame.Rect

What does this mean, and what am I doing wrong?

回答1:

The error means that it is expecting a surface not a rectangle. This is the offending line:

screen.blit(line,(mousex,mousey))

The problem is that you are assigning the result of draw.line() to line.

line=pygame.draw.line(background, (255,255,255), (30,31), (20,31))

From the pygame docs:

All the drawing functions respect the clip area for the Surface, and will be constrained to that area. The functions return a rectangle representing the bounding area of changed pixels.

So you are assigning a rectangle to line. Not sure exactly what you want to do, but you can draw the line following the mouse in the following way:

pygame.draw.line(background, (255,255,255), (x,y), (x,y+10))


回答2:

You use pygame.draw.line wrong. You seem under the impression this returns a new image with the line drawn on background. It doesn't. It will modify the background image.

So instead, you should

  • create a new surface "line" with the required dimensions, and full transparency
  • draw your line on that surface
  • use this then, not the return-value of pygame.draw.line


标签: python pygame