下面的代码在使用 Python 3.10 的 Windows 10 上运行良好。当你点击乌龟时,它的颜色就会改变。但是,当我在基于浏览器的 Trinket 环境中运行代码时,此处:https://trinket.io/python/0da2ab1181,我收到以下错误:
ExternalError: TypeError: Cannot read properties of undefined (reading 'constructor') on line 15 in main.py
当我点击海龟时。
请问我怎样才能正确地工作?我查看了该模块的文档,他们给出了:
Help on function fillcolor in turtle:
turtle.fillcolor = fillcolor(*args)
Return or set the fillcolor.
Arguments:
Four input formats are allowed:
- fillcolor()
Return the current fillcolor as color specification string,
possibly in hex-number format (see example).
May be used as input to another color/pencolor/fillcolor call.
- fillcolor(colorstring)
s is a Tk color specification string, such as "red" or "yellow"
- fillcolor((r, g, b))
*a tuple* of r, g, and b, which represent, an RGB color,
and each of r, g, and b are in the range 0..colormode,
where colormode is either 1.0 or 255
- fillcolor(r, g, b)
r, g, and b represent an RGB color, and each of r, g, and b
are in the range 0..colormode
If turtleshape is a polygon, the interior of that polygon is drawn
with the newly set fillcolor.
Example:
>>> fillcolor('violet')
>>> col = pencolor()
>>> fillcolor(col)
>>> fillcolor(0, .5, 0)
程序代码:
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.io 海龟库中,像
fillcolor()
是 pencolor()
这样的函数只是 setters,而不是像标准 Python 海龟库中那样同时具有 setter 和 getters。因此,正如@jasonharper 建议的(+1),我们需要明确地跟踪颜色状态:
class ToggleTurtle(turtle.Turtle):
COLOR_1 = "red"
COLOR_2 = "blue"
def __init__(self):
super().__init__()
self.shape("turtle")
self.current_color = self.COLOR_1
self.fillcolor(self.current_color)
self.onclick(self.toggle_color)
def toggle_color(self, x, y):
if self.current_color == self.COLOR_1:
self.current_color = self.COLOR_2
else:
self.current_color = self.COLOR_1
self.fillcolor(self.current_color)