簡體   English   中英

python中的Turtle模塊沒有導入

[英]Turtle Module in python not importing

這是我第一次在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”。

所以當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 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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM