Python中的海龟模块未能导入

7

这是我第一次在Python中使用turtle模块,但我似乎无法导入它?
以下是我的代码:

from turtle import *

pen1 = Pen()
pen2 = Pen()

pen1.screen.bgcolour("#2928A7") 

这是我遇到的错误:

Traceback (most recent call last):
  File "C:\Python34\Python saves\turtle.py", line 2, in <module>
    from turtle import *
  File "C:\Python34\Python saves\turtle.py", line 5, in <module>
    pen1 = Pen()
NameError: name 'Pen' is not defined

有谁能告诉我我做错了什么吗?


看起来 turtle.py 是你的程序名称。是这样吗? - PM 2Ring
1
我认为你实际上想使用 pen 而不是 Pen,另外我认为你不能将多个笔存储为对象。 - SuperBiasedMan
@SuperBiasedMan:很可能;有点令人困惑,因为“Pen”是“Turtle”类的别名。 - PM 2Ring
@PM2Ring 是的,如果你能将多个笔保存为类,那么使用大写 P 会很合理,但文档建议 pen() 是一个用于与唯一存在的笔属性交互的函数。 - SuperBiasedMan
在这种情况下,要做的是“Pen”(不是“pen”)。命名自己的源文件为“turtle.py”不是正确的做法。 - cdlane
相关链接:https://dev59.com/R1oV5IYBdhLWcg3wc-Ym - PM 2Ring
2个回答

6
问题在于你将程序命名为"turtle.py"。
因此,当Python遇到语句
from turtle import *
第一个匹配的名为turtle的模块是你自己的程序,即"turtle.py"。
换句话说,你的程序基本上是在导入自己,而不是海龟图形模块。
下面的代码演示了这个问题。

turtle.py

#! /usr/bin/env python

''' Mock Turtle

    Demonstrate what happens when you give your program the same name
    as a module you want to import.

    See https://dev59.com/i47ea4cB1Zd3GeqPAmaP

    Written by PM 2Ring 2015.08.24
'''

import turtle

foo = 42
print(turtle.foo)
help(turtle)

我猜我应该展示一下那段代码实际上会打印什么...

当作为 turtle.py 运行时,它会输出以下的 "help" 信息:

Help on module turtle:

NAME
    turtle - Mock Turtle

FILE
    /mnt/sda4/PM2Ring/Documents/python/turtle.py

DESCRIPTION
    Demonstrate what happens when you give your program the same name
    as a module you want to import.

    See https://dev59.com/i47ea4cB1Zd3GeqPAmaP

    Written by PM 2Ring 2015.08.24

DATA
    foo = 42

(END) 

当您按下 Q 键退出帮助时,帮助信息将再次显示。第二次按下 Q 键,则...

42

42

打印出来了。

为什么“help”信息和42被打印了两次?这是因为在导入turtle.py时,其中的所有代码都会被执行,然后在import语句之后再次执行。请注意,Python不会尝试导入已经导入的模块(除非使用reload显式告诉它这样做)。如果Python重新导入模块,则上述代码将陷入无限循环的导入中。


mockturtle.py运行时,它会打印:

Traceback (most recent call last):
  File "./mock_turtle.py", line 16, in <module>
    print(turtle.foo)
AttributeError: 'module' object has no attribute 'foo'

当然,这是因为标准的turtle模块实际上没有foo属性。


-1
我认为解决方案是输入以下内容:

pen1 = turtle.Pen()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接