Trinket平台Turtle图形实现报错TypeError的解决咨询
Trinket环境下Turtle点击切换颜色报错的修复方案
问题背景
在Windows 10 + Python 3.10的本地环境里,下面的代码能正常运行,点击海龟图形就能切换它的颜色;但放到浏览器的Trinket环境中运行时,一点击海龟就会弹出错误:
ExternalError: TypeError: Cannot read properties of undefined (reading 'constructor') on line 15 in main.py
原代码如下:
class ToggleTurtle(turtle.Turtle): def __init__(self): super().__init__() self.shape("turtle") self.color1 = "red" self.color2 = "blue" self.fillcolor(self.color1) self.onclick(self.toggle_color) def toggle_color(self, x, y): if self.fillcolor() == self.color1: self.fillcolor(self.color2) else: self.fillcolor(self.color1) tt = ToggleTurtle() turtle.done()
问题原因
Trinket用的是基于浏览器的turtle实现,和本地Python的标准turtle库存在兼容性差异:本地调用无参的fillcolor()会返回颜色字符串(比如"red"),但在Trinket里,这个方法返回的可能是无法直接和字符串比较的对象,导致判断颜色相等时触发类型错误。
修复方案
别再靠fillcolor()的返回值判断当前颜色,改成自己维护一个状态变量来追踪当前颜色:
修改后的代码:
import turtle class ToggleTurtle(turtle.Turtle): def __init__(self): super().__init__() self.shape("turtle") self.color1 = "red" self.color2 = "blue" self.current_color = self.color1 # 用这个变量记录当前颜色 self.fillcolor(self.current_color) self.onclick(self.toggle_color) def toggle_color(self, x, y): # 直接判断状态变量,不用调用fillcolor() if self.current_color == self.color1: self.current_color = self.color2 else: self.current_color = self.color1 self.fillcolor(self.current_color) # 根据状态设置新颜色 tt = ToggleTurtle() turtle.done()
说明
通过新增current_color变量手动记录当前颜色,完全绕开了Trinket环境中fillcolor()返回值的兼容性问题,不管是本地还是Trinket环境,代码都能正常运行,点击海龟就能切换颜色。
内容的提问来源于stack exchange,提问作者Robin Andrews
相关产品推荐
相关产品推荐

