Python中的海龟模块无法导入。

2024-05-21 08:25:17 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我第一次在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

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


Tags: 模块代码infrompyimportlinefile
2条回答

问题是你把你的程序命名为“turtle.py”。

所以当Python看到语句
from turtle import *
它找到的第一个名为turtle的匹配模块是您的程序“turtle.py”。

换句话说,你的程序基本上是自己导入,而不是海龟图形模块。


这里有一些代码来演示这个问题。

海龟.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 http://stackoverflow.com/q/32180949/4014959

    Written by PM 2Ring 2015.08.24
'''

import turtle

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

我想我应该展示代码实际打印的是什么。。。

当运行方式为turtle.py时,它会打印以下“帮助”信息:

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 http://stackoverflow.com/q/32180949/4014959

    Written by PM 2Ring 2015.08.24

DATA
    foo = 42

(END) 

当您点击Q退出帮助时,将再次显示帮助信息。当你第二次点击Q时,那么

42

42

是印刷品。

为什么“帮助”信息和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属性。

我认为解决方法是键入:

pen1 = turtle.Pen()

相关问题 更多 >