Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"module 'pygame' has no attribute 'init'" running a simple pygame script [duplicate]

Tags:

python

pygame

When i run my pygame code, i get the following error:

>>> 
 RESTART: C:/Users/lanra/Desktop/2018 backups/2018 python/pygame/pygame 2.py 
Traceback (most recent call last):
  File "C:/Users/lanra/Desktop/2018 backups/2018 python/pygame/pygame 2.py", line 1, in <module>
    import pygame
  File "C:/Users/lanra/Desktop/2018 backups/2018 python/pygame\pygame.py", line 3, in <module>
    pygame.init()
AttributeError: module 'pygame' has no attribute 'init'

My code:

import pygame
pygame.init()

win = pygame.display.set_mode((500,500))

pygame.display.set_caption("first game")

x = 50
y = 50
width = 40
height = 60
vel = 5

run= True
while run:
    pygame.time.delay(100)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False


    pygame.draw.rect(win, (255,0,0))

    pygame.quit()
like image 477
DragonProgram Avatar asked Jun 12 '26 05:06

DragonProgram


1 Answers

Looks like you have a script called pygame.py locally to your test script. This is getting imported instead of the library.

The fix is to rename your local pygame.py script (which is presumably another version of this one as you are figuring out Pygame) so it does not conflict. In general, avoid naming your project files the same as the libraries that you are using.

You also have other errors in your code (please read the Pygame documentation and examples), but this will be the first fix you need to apply, and it is not specific to Pygame.

Here is a working version of your code:

import pygame
pygame.init()

win = pygame.display.set_mode((500,500))

pygame.display.set_caption("first game")

x = 50
y = 50
width = 40
height = 60
vel = 5

while True:
    pygame.time.delay(100)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()

    pygame.draw.rect(win, (255,0,0), win.get_rect())

    pygame.display.update()

Note the extra required param to pygame.draw.rect and call to pygame.display.update(). Also modified the while loop, as once you have called pygame.quit() you don't want to call things like pygame.event.get() else you will get error messages about no video system.

like image 110
Neil Slater Avatar answered Jun 13 '26 17:06

Neil Slater