使用Turtle库的OOP版Pong游戏出现KeyError,如何解决?
Pong游戏KeyError问题解决
你的代码出现KeyError的核心原因是Paddle类的初始化方法拼写错误,把Python类的标准初始化方法__init__误写成了__int__,导致Paddle实例无法被正确初始化。
修正步骤
- 修复Paddle类的构造函数拼写
将__int__改为__init__,修正后的Paddle文件代码:
from turtle import Turtle class Paddle(Turtle): def __init__(self, position): super().__init__() self.shape("square") self.color("white") self.shapesize(stretch_wid=5, stretch_len=1) self.penup() self.goto(position) def go_up(self): new_y = self.ycor() + 20 self.goto(self.xcor(), new_y) def go_down(self): new_y = self.ycor() - 20 self.goto(self.xcor(), new_y)
- 添加游戏刷新循环(必要补充)
因为你关闭了turtle的自动动画(screen.tracer(0)),需要手动添加循环刷新画面,否则 paddle 移动后不会实时显示。在主文件的screen.listen()之后添加:
while True: screen.update()
错误原因解释
Python中,类的初始化方法必须是__init__(双下划线包裹的init),你写的__int__是一个自定义方法,不会在实例化对象时自动执行。这导致Paddle实例没有执行初始化逻辑,本质上只是一个未正确配置的Turtle对象,后续调用go_up/go_down时,Turtle内部的属性未正确初始化,从而触发KeyError。
内容的提问来源于stack exchange,提问作者Milla Dma
相关产品推荐
相关产品推荐

