You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决Python代码中出现的TypeError: 'int' object is not subscriptable错误?

Fixing the 'int' object is not subscriptable Error in Your Player Class

Let's break down what's causing this error and how to fix it:

The Root Cause

Looking at your code, the problem stems from an inconsistent structure for self.pos:

  • In __init__, you initialize self.pos = [(self.x, self.y)] — this is a list containing a coordinate tuple (e.g., [(607, 420)]).
  • But in the movement method, you overwrite it with self.pos = [self.x, self.y] — this becomes a list of two integers (e.g., [610, 420]).

When your draw method runs for tup in self.pos:

  • Right after initialization, tup is the tuple (607, 420), so accessing tup[0] works perfectly.
  • After calling movement, self.pos is a list of integers. The loop first grabs the integer value of self.x, then tries to run tup[0] — which throws the error because integers don't support subscripting (you can't index into an int like you would a list or tuple).

Solution 1: Keep self.pos as a list of coordinate tuples (for tracking movement history)

If you want to track all previous positions (e.g., to draw a movement trail), update movement to append new coordinate tuples instead of replacing the entire list:

def movement(self, x, y):
    self.x += x
    self.y += y
    self.pos.append((self.x, self.y))  # Add new tuple to the list, don't overwrite it

This keeps self.pos as a list of tuples, so your draw loop will function as intended. (Note: Your current draw logic only renders the current position — you might want to adjust this if you want to draw the full trail.)

Solution 2: Simplify self.pos to hold just the current coordinate tuple

Since your current draw logic only renders the current x,y position, there's no need for a list. You can simplify the code to use a single tuple for self.pos:

class Player(object):
    def __init__(self, board):
        self.board = board
        self.x = 607
        self.y = 420
        self.pos = (self.x, self.y)  # Single tuple for current position
    def movement(self, x, y):
        self.x += x
        self.y += y
        self.pos = (self.x, self.y)  # Update the tuple with new coordinates
    def draw(self):
        # No loop needed — draw the current position directly
        pygame.draw.circle(self.board.window, (255, 255, 0), self.pos, 8)
    def update(self):
        pygame.display.update()

This is cleaner and eliminates the type mismatch entirely.

Key Takeaway

Always keep your variable structures consistent! If you start with a list of tuples, don't suddenly switch to a list of integers halfway through your code — this kind of type inconsistency is a common source of errors like this.


内容的提问来源于stack exchange,提问作者George Dimitriou

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:45:07