首页 > 解决方案 > “TypeError:'NoneType' 对象不可下标”是什么意思?

问题描述

我正在 Python3 中使用 Pygame 编写蛇游戏。但是,我不断收到这个 TypeError,我不仅不知道这意味着什么,我也不知道如何修复它

我没有真正尝试过任何事情,因为我不知道它是什么或如何解决它。这是代码:

def draw(self, surface, eyes=False):
    dis = self.w // self.rows
    i = self.pos[0]
    j = self.pos[1]

我不断收到的错误消息是:

pygame 1.9.6
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
File "snake.py", line 179, in <module>
main()
File "snake.py", line 175, in main
redrawWindow(win)
File "snake.py", line 127, in redrawWindow
snack.draw(surface)
File "snake.py", line 25, in draw
i = self.pos[0]
TypeError: 'NoneType' object is not subscriptable

标签: python-3.xpygame

解决方案


当您尝试通过 Nonetype 对象进行索引时会发生这种情况,例如,

>>> x = None
>>> x[0]
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    x[0]
TypeError: 'NoneType' object is not subscriptable

为了正确解决您的问题,请发布完整代码或您设置的初始值self.pos。您似乎将此变量设置为None.


推荐阅读