如何解决Python代码中出现的TypeError: 'int' object is not subscriptable错误?
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 initializeself.pos = [(self.x, self.y)]— this is a list containing a coordinate tuple (e.g.,[(607, 420)]). - But in the
movementmethod, you overwrite it withself.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,
tupis the tuple(607, 420), so accessingtup[0]works perfectly. - After calling
movement,self.posis a list of integers. The loop first grabs the integer value ofself.x, then tries to runtup[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

