3

当我尝试运行Python 文档中turtle的第一段示例代码时:

from turtle import *
color('red', 'yellow')
begin_fill()
while True:
    forward(200)
    left(170)
    if abs(pos()) < 1:
        break
end_fill()
done()

我得到一个NameError

NameError:名称“颜色”未定义

调整import和手动指定模块也不起作用:

import turtle
turtle.color('red', 'yellow')
turtle.begin_fill()
while True:
    turtle.forward(200)
    turtle.left(170)
    if abs(turtle.pos()) < 1:
        break
turtle.end_fill()
turtle.done()

根据文档,我正在使用 Python v3.2.3,它显然包含turtle.color。Python 也安装了tkinter支持,因为import tkinter它也能正常工作。

完整的跟踪是:

Traceback (most recent call last):
  File "<path name that contains no spaces>/turtle.py", line 1, in <module>
    from turtle import *
  File "<path name that contains no spaces>\turtle.py", line 2, in <module>
    color('red', 'yellow')
NameError: name 'color' is not defined

多么奇怪。如果我进入 shell,无论是命令行还是 IDLE,然后一次输入一个命令:

>>> from turtle import *
>>> color('red', 'yellow')

没有问题。只有当我在 IDLE 中打开一个新窗口,输入所有命令并运行脚本时。

4

1 回答 1

15

您将文件命名为“turtle.py”,因此当您import turtle导入自己的文件而不是 stdlib 模块时。更改程序的名称,并删除该目录中的所有 .pyc 文件。

于 2012-07-05T16:29:01.900 回答