Python says pygames has no attribute 'init()&#

2019-08-02 02:47发布

问题:

I'm using Python 2.7 with pygame-1.9.2pre.win32-py2.7.‌exe from http://www.lfd.uci.edu/~gohlke/pythonlibs/#pygame

I've run this script:

import pygame
print 'PyGame Version: %s ' % pygame.__version__

to see if my module was installed correctly and I got:

PyGame Version: 1.9.2pre 

As far as I know, it means that pygame is working correctly. In Python IDLE i try to run interactively:

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

And it works fine. But whenever I try to run this as a script I get:

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'

On Eclipse or Running in IDLE either. What this could be?

回答1:

If your script is named pygame.py Python will import it instead of the actual pygame package (when you do import pygame). That might explain your error.



回答2:

when you named your script pygame.py and tried to run it, python created a file name "pygame.pyc" (=python compiled file) and put it in the directory you saved your pygame.py script.

you have to remove the newley created .pyc file and rename your script to somthing like my_py_game.py instead of pygame.py