这是我第一次在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
from turtle import *
File "C:\Python34\Python saves\turtle.py", line 5, in
pen1 = Pen()
NameError: name 'Pen' is not defined
谁能告诉我我做错了什么?
解决方法:
问题是你已经将你的程序命名为“turtle.py”.
所以当Python看到这个陈述时
来自龟进口*
它找到的第一个名为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://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 https://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不会尝试导入已导入的模块(除非明确告知重新加载).如果Python重新导入,那么上面的代码将陷入无限的导入循环.
当以mockturtle.py运行时,它会打印:
Traceback (most recent call last):
File "./mock_turtle.py", line 16, in
print(turtle.foo)
AttributeError: 'module' object has no attribute 'foo'
当然那是因为标准的海龟模块实际上没有foo属性.
标签:python,turtle-graphics
来源: https://codeday.me/bug/20190623/1272680.html