Python Turtle迷宫开发报错:AttributeError: 'int'对象无'_goto'属性
Hey there! Let's break down what's causing that error and fix it step by step.
The Root Cause
The error pops up because you're trying to call the goto() method directly on the End class instead of an instance of that class. Methods like goto() are instance methods—they need to be called on an object created from the class, not the class itself. When you use End.goto(), Python can't identify which turtle object you're targeting, leading to that confusing AttributeError.
How to Fix It
Follow these simple changes to get your maze working:
Create an instance of the End class
Just like you did with thePenclass, make an object ofEndbefore using it in your maze setup:end = End()Update the setup_maze function
ReplaceEnd.goto()andEnd.stamp()with your newendinstance—this tells Python exactly which turtle to move:if character == "s": end.goto(screen_x, screen_y) end.stamp()Fix your level layout
Yourlevel_1strings had inconsistent lengths, which would mess up the maze's alignment. Let's make them all 12 characters long to match the first line:level_1 = [ "XXXXXXXXXXXX", "X...X..X..eX", "X.X....X.XXX", "X..X.X.X.X.X", "XX.XXX.X...X", "X........X.X", "XsXX...X...X", "XXXXXXXXXXXX" ]Replace the infinite while loop
A barewhile True: passwill freeze your program. Use Turtle's built-in main loop instead to keep the window responsive:wn.mainloop()
Full Corrected Code
Here's the updated code with all fixes applied:
import turtle wn = turtle.Screen() wn.bgcolor("black") wn.title("A Maze Game") wn.setup(700,700) class Pen(turtle.Turtle): def __init__(self): turtle.Turtle.__init__(self) self.shape("square") self.color("white") self.penup() self.speed(0) class End(turtle.Turtle): def __init__(self): turtle.Turtle.__init__(self) self.shape("square") self.color("green") self.penup() self.speed(0) levels = [""] level_1 = [ "XXXXXXXXXXXX", "X...X..X..eX", "X.X....X.XXX", "X..X.X.X.X.X", "XX.XXX.X...X", "X........X.X", "XsXX...X...X", "XXXXXXXXXXXX" ] levels.append(level_1) def setup_maze(level): for y in range(len(level)): for x in range(len(level[y])): character = level[y][x] screen_x = -288 + (x * 24) screen_y = 288 - (y * 24) if character == "X": pen.goto(screen_x, screen_y) pen.stamp() if character == "s": end.goto(screen_x, screen_y) end.stamp() pen = Pen() end = End() # Create instance of End class setup_maze(levels[1]) wn.mainloop() # Use Turtle's main loop instead of infinite while
Bonus Tip
If you want to add the "e" endpoint later, you can reuse the end instance or create a separate one—just remember: always call turtle methods on an instance of the class, not the class itself!
内容的提问来源于stack exchange,提问作者stackex123

