Python Turtle报错Expected type 'str' got tuple[int,int]咨询
报错根因
触发Expected type 'str', got 'tuple[int, int]' instead报错的核心原因是Paddle类的构造方法名拼写错误:
- Python类的初始化构造方法固定命名为
__init__(方法名前后各两个下划线,中间为init,是initialize的缩写) - 你的Paddle类中错写为
def __int__(self, position):,将init拼为了int,导致实例化Paddle传入坐标元组时,自定义的初始化逻辑完全没有执行,直接调用了父类Turtle的构造方法。 - Turtle父类构造方法的第一个参数是形状配置项,要求传入字符串类型,你传入的
(-200, 0)、(350, 0)为元组类型,类型不匹配直接触发该报错。
修复方法
将Paddle类中拼写错误的构造方法名修正即可,修改后的Paddle类代码如下:
from turtle import Turtle class Paddle(Turtle): def __init__(self, position): super().__init__() self.shape("square") self.color("white") self.shapesize(stretch_len=1.0, stretch_wid=5.0) 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)
补充优化建议
你的main.py中已经导入了time模块但未使用,当前无延时的游戏循环会占用极高CPU资源,建议在循环内补充帧率控制逻辑:
while game_is_on: time.sleep(0.1) screen.update()
内容的提问来源于stack exchange,提问作者Kenny Okoye
相关产品推荐
相关产品推荐

