Python 乌龟无效命令(来自 Think Python 书)

Python turtle invalid command (From Think Python book)

我正在尝试按照 "Think Python" 书中的练习和 运行 解决一个问题,试图让 turtle 工作。 Here is the exercise I'm on. (4.1)

他们要我执行的代码如下所示:

import turtle
bob = turtle.Turtle()
print(bob)
turtle.mainloop()

bob.fd(100)
bob.lt(90)
bob.fd(100)

但是当我执行它时,海龟没有移动,当我关闭 window 时出现以下错误:

Traceback (most recent call last):
    File "C:\Users\Phil\PycharmProjects\untitled\mypolygon.py", line 6, in <module>
        bob.fd(100)
    File "C:\Python.5\lib\turtle.py", line 1637, in forward
        self._go(distance)
    File "C:\Python.5\lib\turtle.py", line 1605, in _go
        self._goto(ende)
    File "C:\Python.5\lib\turtle.py", line 3158, in _goto
        screen._pointlist(self.currentLineItem),
    File "C:\Python.5\lib\turtle.py", line 755, in _pointlist
        cl = self.cv.coords(item)
    File "<string>", line 1, in coords
    File "C:\Python.5\lib\tkinter\__init__.py", line 2308, in coords
        self.tk.call((self._w, 'coords') + args))]
_tkinter.TclError: invalid command name ".1395635997272"

我不确定调试器在说什么,在弄清楚哪里出错之前我无法继续。任何帮助将不胜感激。

bob.fd(100) 行(以及所有后续行)永远不会到达,因为 turtle.mainloop() 调用开始一个循环(顾名思义)。

更改您的代码,使其显示为:

import turtle
bob = turtle.Turtle()
print(bob)

bob.fd(100)
bob.lt(90)
bob.fd(100)

一切都应该正常。

(因为你没有在你的程序中处理任何事件,我建议暂时不要调用 turtle.mainloop();如果你确实想按照书中的例子,一定要按照它说的去做:“要绘制直角,将这些行添加到程序中(在创建 bob 之后和在调用 mainloop 之前)")。

有类似问题here, here and here