Python - Pygame AttributeError:int对象没有属性' draw'

时间:2017-08-27 19:09:19

标签: python python-3.x attributes pygame attributeerror

我想为draw的每个项目调用movemy_list方法。我尝试了my_objects.draw()my_objects.move()而不是i.draw()i.move(),但我总是得到同样的错误。这是我的代码:

import pygame
import random

BLACK = (0, 0, 0)
GREEN = (0, 255, 0)

class Rectangle():
    def __init__(self):
        self.x = random.randrange(0, 700)
        self.y = random.randrange(0, 500)
        self.height = random.randrange(20, 70)
        self.width = random.randrange(20, 70)
        self.change_x = random.randrange(-3, 3)
        self.change_y = random.randrange(-3, 3)

    def move(self):
        self.x += self.change_x
        self.y += self.change_y

    def draw(self):
        pygame.draw.rect(screen, GREEN, [self.x, self.y, self.width, self.height])

my_list = []

for number in range(10):
    my_object = Rectangle()
    my_list.append(my_object)

pygame.init()

screen = pygame.display.set_mode((700, 500))  
done = False
clock = pygame.time.Clock()

while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

    screen.fill(BLACK)

    for i in range(len(my_list)):
        number.draw()
        number.move()

    pygame.display.flip()
    clock.tick(60)

pygame.quit()

这是错误:

Traceback (most recent call last):
  line 53, in <module>
  number.draw()
AttributeError: 'int' object has no attribute 'draw'

1 个答案:

答案 0 :(得分:1)

您正在迭代索引。但你真的想要遍历项目。所以你不需要range(len(...))构造。而是使用for item in items。试试这个:

for rect in my_list:
    rect.draw()
    rect.move()