微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

按钮不在事件内?

如何解决按钮不在事件内?

我正在为我的 xBox one 控件使用 pygame,应该有一个名为按钮的东西,但它抛出一个错误,说 AttributeError: 'Event' object has no attribute 'button'

这是完整的代码

import pygame
pygame.init()
joysticks = []
clock = pygame.time.Clock()
keepPlaying = True

# for al the connected joysticks
for i in range(0,pygame.joystick.get_count()):
    # create an Joystick object in our list
    joysticks.append(pygame.joystick.Joystick(i))
    # initialize them all (-1 means loop forever)
    joysticks[-1].init()
    # print a statement telling what the name of the controller is
    print ("Detected joystick "),joysticks[-1].get_name(),"'"
while keepPlaying:
    for event in pygame.event.get():
        print(event)
        if event.button == 0:
            print ("A Has Been pressed")

当我按下 a 它打印 <Event(1539-JoyButtonDown {'joy': 0,'instance_id': 0,'button': 0})> 应该有一个按钮 attrabute 但它会抛出错误

解决方法

每种事件类型都会生成一个具有不同属性的 pygame.event.Event 对象。并非为所有事件对象都定义了 button 属性。您可以从鼠标或操纵杆事件(如 buttonJOYBUTTONUP)中获取 JOYBUTTONDOWN 属性。但是,所有事件对象都具有 type 属性。检查 type 属性之前的事件 button 属性(请参阅 pygame.event):

while keepPlaying:
    for event in pygame.event.get():
        print(event)
        if event.type == JOYBUTTONDOWN:
            if event.button == 0:
                print ("A Has Been Pressed")

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。