Turtle Module in python does not import

This is my first time using the turtle module in python, but I can not import it?
Here is my code:

from turtle import *

pen1 = Pen()
pen2 = Pen()

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

and here is the error I get:

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

Can someone tell me what I did wrong?

+4
source share
2 answers

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

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

In other words, your program basically imports itself, not the turtle's graphics module.


Here is the code demonstrating 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)

, , ...

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

.

"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.

+4

, , :

pen1 = turtle.Pen()
-1

All Articles