python - 当我尝试使用 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'
解决方案
在 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 *
。
推荐阅读
- javascript - 当我尝试将多个点击侦听器添加到标记 django 时,initMap 不是一个函数
- javafx - 条形图无法正确显示
- r - 如何根据 R 中的另一个数据框更改数据框中的值?
- android - 对话框全屏布局问题
- php - Laravel:更新身份验证用户数据然后显示视图
- javascript - 调用异步函数的客户端代码是否需要使用等待?
- python-3.x - 当我使用 pow 和 mod 时,如何防止 Python 自动将 int 转换为 float?
- ajax - 使用 Coldfusion、Ajax 和 CFC 进行数据查找
- react-native - React Native Firebase + Redux(额外的 userProfile 信息)
- multithreading - 有人可以解释运行空间 PSThreadOptions 吗?