Python提示pygame没有'init()'属性,但库已正确安装
我正在使用 Python 2.7
和从 http://www.lfd.uci.edu/~gohlke/pythonlibs/#pygame 下载的 pygame-1.9.2pre.win32-py2.7.exe
。
我运行了这个脚本:
import pygame
print 'PyGame Version: %s ' % pygame.__version__
是为了检查我的模块是否安装正确,结果我得到了:
PyGame Version: 1.9.2pre
据我所知,这意味着pygame工作正常。在Python的IDLE环境中,我尝试交互式运行:
import pygame
pygame.init()
# Set the height and width of the screen
size=[700,500]
screen=pygame.display.set_mode(size)
pygame.display.set_caption("My Game")
结果也很好。但是每当我尝试把它作为脚本运行时,我就会得到:
Traceback (most recent call last):
File "D:\Computing\Workspaces\Python\test\pygame.py", line 5, in <module>
import pygame
File "D:\Computing\Workspaces\Python\test\pygame.py", line 13, in <module>
pygame.init()
AttributeError: 'module' object has no attribute 'init'
在Eclipse或者IDLE中运行也是这样。这可能是什么原因呢?
2 个回答
0
当你把你的脚本命名为 pygame.py 并尝试运行它时,Python 会创建一个名为 "pygame.pyc" 的文件(这个文件是 Python 编译后的文件),并把它放在你保存 pygame.py 脚本的文件夹里。
你需要删除这个新创建的 .pyc 文件,并把你的脚本重命名为像 my_py_game.py 这样的名字,而不是 pygame.py。
6
如果你的脚本文件叫做 pygame.py
,那么当你执行 import pygame
的时候,Python 会优先导入你这个文件,而不是实际的 pygame
库。这可能就是你遇到错误的原因。