运行简单的pygame脚本的“模块'pygame'没有属性'init'”

时间:2018-09-26 09:54:46

标签: python pygame

运行pygame代码时,出现以下错误:

>>> 
 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'

我的代码:

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

1 个答案:

答案 0 :(得分:1)

似乎您的测试脚本本地有一个名为pygame.py的脚本。这是导入而不是库。

解决方法是重命名您的本地pygame.py脚本(在确定Pygame时可能是该脚本的另一个版本),因此不会发生冲突。通常,请避免将项目文件命名为与正在使用的库相同的名称。

您的代码中还存在其他错误(请阅读Pygame文档和示例),但这将是您需要应用的第一个修复程序,并非特定于Pygame。

这是您代码的有效版本:

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

请注意pygame.draw.rect的额外必需参数,然后调用pygame.display.update()。还修改了while循环,因为一旦调用pygame.quit(),您就不想调用pygame.event.get()之类的东西,否则您将收到有关没有视频系统的错误消息。