类型错误:'int' 对象没有属性 '__getitem__' [英] TypeError: 'int' object has no attribute '__getitem__'

查看:86
本文介绍了类型错误:'int' 对象没有属性 '__getitem__'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用 pygame 中的 rect 制作游戏表面.我不确定问题到底是什么,但我相信它与创建 rect 时列表的实际迭代有关.对不起,菜鸟在这里.:)

I'm trying to make a play surface out of rects in pygame. I'm not sure what the problem is exactly but I believe it has something to do with the actual iteration of the list when creating the rects. Sorry, noob here. :)

import pygame

w = 800
h = 600
board_pos = 0, 0
tile = 27
playfield = 0

class Board(object):
    def __init__(self, surface, pos, tile_size):
        self.surface = surface
        self.x, self.y = pos
        self.tsize = tile_size
        self.color = 50, 50, 50

        playfield = [list(None for i in xrange(22)) for i in xrange(10)]  

    def draw(self):
        for i in xrange(10):
            for j in xrange(22):
                playfield[i][j] = pygame.draw.rect(self.surface, self.color,
                                                  (self.x + (i * self.tsize),
                                                   self.y + (j * self.tsize),
                                                   self.tsize, self.tsize))

pygame.display.init()
screen = pygame.display.set_mode((w, h))

board = Board(screen, board_pos, tile)
board.draw()

while __name__ == '__main__':
    pygame.display.flip()

我不断收到此错误:

Traceback (most recent call last):
  File "C:\Documents and Settings\Administrator\My
Documents\Dropbox\Programming\DeathTris
\test2.py", line 30, in <module>
    board.draw()
  File "C:\Documents and Settings\Administrator\My
Documents\Dropbox\Programming\DeathTris
\test2.py", line 24, in draw
    self.tsize, self.tsize))
TypeError: 'int' object has no attribute '__getitem__'

任何帮助将不胜感激.谢谢!

Any help would be appreciated. Thanks!

推荐答案

Your line playfield = [list(None for i in xrange(22)) for i in xrange(10)]__init__ 函数内的局部变量.该变量在 __init__ 函数返回后消失.稍后在 draw 中,当您执行 playfield[i][j] 时,您正在访问 playfield 的全局值,该值仍然为 0(因为您在开始时将其初始化为 0).

Your line playfield = [list(None for i in xrange(22)) for i in xrange(10)] creates a local variable inside the __init__ function. That variable disappears after the __init__ function returns. Later in draw when you do playfield[i][j], you are accessing the global value of playfield, which is still 0 (since you initialized it to 0 at the beginning).

如果您想从 __init__ 内部覆盖全局 playfield,则需要在分配给它之前执行 global playfield.(但是......你为什么要为此使用全局变量?)

If you want to overwrite the global playfield from inside your __init__, you need to do global playfield before you assign to it. (But. . . why are you using a global variable for this anyway?)

这篇关于类型错误:'int' 对象没有属性 '__getitem__'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆