首页 > 解决方案 > 当我尝试使用 event.type 时,它​​说“模块”对象没有类型属性

问题描述

当我尝试使用 event.type 时,它​​会这么说。虽然我之前没有使用过事件模块,但它在我的书中说它应该可以工作。我在谷歌和堆栈溢出上查找了这个,但我没有找到类似的东西(我使用 Javascript 作为代码片段,因为我不知道如何将代码放入 python。)

import pygame
from pygame import *
pygame.init()
pygame.event.get()
black = (0,0,0)
white = (255,255,255)
playercoords_a = (275,425)
playercoords_b = (275,475)
playercoords_c = (225,475)
playercoords_d = (225,425)
playertotalcoords = (playercoords_a, playercoords_b, playercoords_c, playercoords_d)
windowSurface = pygame.display.set_mode((500, 500),0,32)
windowSurface.fill(black)
xmod = 0
ymod = 0
pygame.draw.polygon(windowSurface,white,((275,425),(275,475),(225,475),(225,425)))
pygame.display.update()
while True:
    if event == KEYDOWN:
        if event.key == K_LEFT:
            print('it works')
        windowSurface.fill((black,))
        pygame.draw.polygon(windowSurface,white,((275 + xmod,425 + ymod),(275 + xmod,475 + ymod),(225 + xmod,475 + ymod),(225 + xmod,425 + ymod)))
        pygame.display.update()

第 19 行,在
if event.type == KEYDOWN:
AttributeError: 'module' object has no attribute 'type'

标签: pythonpython-3.xpygame

解决方案


在 pygame 中,您通常有一个for用于事件处理的循环,在您的情况下,它应该如下所示:

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                print('it works')
...

在这种情况下,事件是pygame.event.get()从而不是模块返回的事件对象。


你所做的是将 pygame 的event模块导入到全局命名空间中from pygame import *。所以当你跑

while True:
    if event == KEYDOWN:

event实际上就是这个模块,而不是实际的事件对象。

永远不要from pygame import *


推荐阅读