Cant find Pygame Module

2019-03-06 00:34发布

问题:

I just started game developing in python with pygame and I have the following code:

bif="main_background.jpg"
mif="player_head.png"

import pygame, sys
from pygame.locals import *

pygame.init()
screen=pygame.display.set_mode((640,360),0,64)

background=pygame.image.load(bif).convert()
mouse_c=pygame.image.load(mif).convert_alpha()

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

    screen.blit(background, (0,0))

    x,y = pygame.mouse.get_pos()
    x -= mouse_c.get_width()/2
    y -= mouse_c.get_height()/2

    screen.blir(mouse_c,(x,y))

    pygame.display.update()

I get the following error in Python:

Traceback (most recent call last):
  File "C:/Users/Eier/Documents/Code Developments/pygame.py", line 4, in <module>
    import pygame, sys
  File "C:/Users/Eier/Documents/Code Developments\pygame.py", line 5, in <module>
    from pygame.locals import *
ImportError: No module named locals
>>> 

If someone knows how to make python find pygame please reply.

Thank you :)

回答1:

I'm about 83.4% sure that you named your script pygame.py (or possibly created another file with the same name in the same directory as your script).

If you do that, Python has no way of knowing what you want to load when you import pygame. It could be your script, it could be the installed package—they both have the same name.

What ends up happening is that import pygame imports your script, then from pygame.locals import * looks for a module called locals inside your script. Since your script is a script, and not a package, Python just gets confused and prints a confusing ImportError.

Python 3.x gives you some ways around this, but 2.x does not, and I'm guessing you're using 2.x.

So, the solution is:

  • Rename your script to mygame.py.
  • Delete any other files in the same directory as your script named pygame.py.


标签: python pygame