Turtle Module in python not importing

依然范特西╮ 提交于 2019-12-05 16:08:09

The problem is that you've named your program "turtle.py".

So when Python sees the statement
from turtle import *
the first matching module named turtle that it finds is your program, "turtle.py".

In other words, your program is basically importing itself and not the turtle graphics module.


Here's some code to demonstrate this problem.

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

    Written by PM 2Ring 2015.08.24
'''

import turtle

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

I guess I should show what that code actually prints...

When run as turtle.py it prints the following "help" info:

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) 

When you hit Q to get out of the Help, the Help info is displayed again. When you hit Q for the second time, then

42

42

is printed.

Why are the "help" message and 42 printed twice? That's because all the code in turtle.py is executed when it's imported, and then again when its encountered after the import statement. Note that Python doesn't try to import modules that it has already imported (unless explicitly told to do so with reload). If Python did re-import, then the above code would get stuck in an infinite loop of importing.


When run as mockturtle.py it prints:

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

And of course that's because the standard turtle module doesn't actually have a foo attribute.

anonymous programmer

I think the solution is to type this :

pen1 = turtle.Pen()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!