swampy.TurtleWorld 不适用于 python 3.4

swampy.TurtleWorld not working in python 3.4

我目前正在使用 ThinkPython 书学习 python,正在使用 python 3.4 和 Anaconda IDE。我需要继续的部分工作是安装一个名为 swampy 的模块。我使用 pip 安装它,效果很好。导入模块也可以与 tkinter 一起使用,但我无法使用模块中的任何功能。我检查了我的 lib 文件夹,swampy 在那里,函数也在 swampy 文件夹中。我不明白为什么它不起作用。我真的需要帮助。如果问题不够清楚,请告诉我。我已经包含了我尝试 运行 的代码和我每次尝试 运行 时收到的错误消息

我尝试 运行 的代码(第 29 页,第 4 章认为 Python python 3.4 的版本)

import tkinter
import swampy
world = swampy.TurtleWorld
bob = Turtle()
print(bob)
wait_for_user()

我收到错误消息

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\Mbaka1\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 682, in runfile
    execfile(filename, namespace)
  File "C:\Users\Mbaka1\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 85, in execfile
    exec(compile(open(filename, 'rb').read(), filename, 'exec'), namespace)
  File "C:/Users/Mbaka1/Documents/Python Scripts/test.py", line 28, in <module>
    world = swampy.TurtleWorld
AttributeError: 'module' object has no attribute 'TurtleWorld'

如果您下载了源代码,本书会显示以下说明:

from TurtleWorld import *
world = TurtleWorld()
bob = Turtle()
print(bob)
wait_for_user()

如果你想 运行 使用 pip 安装后的代码,这应该可以工作:

from swampy.TurtleWorld import *
world = TurtleWorld()
bob = Turtle()
print(bob)
wait_for_user()

你所做的不起作用的原因是因为 TurtleWorldswampy 包中的一个模块,它包含一个同名的函数,即 TurleWorld .因此,当您执行 import swampy 然后尝试调用 swampy.TurtleWorld 时,您正在尝试调用模块而不是函数。

或者,您可以在此处下载 Think Python 第二版:http://greenteapress.com/wp/think-python-2e/ 它使用 Python3,您不需要 swampy 包来 运行此处给出的示例,因为 turtle 和 tkinter(此处使用)是 Python 标准库的一部分。

我目前也在研究那本书。我通过添加解决了这个问题:

import swampy.TurtleWorld

确保沼泽模块中的 TurtleWorld 模块在您的 shell 中运行。只要您的 Python 版本是 3.4 或 3.5,这就有效。