AttributeError:“事件”对象没有属性“按钮”

2024-06-09 21:28:17 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的代码,我正在尝试运行我的xbox控制器,以便稍后使用if语句来控制直流电机:

pygame.init()
joystick = []
clock = pygame.time.Clock()

for i in range(0, pygame.joystick.get_count()):
    joystick.append(pygame.joystick.Joystick(i))
    joystick[-1].init()
        
while True:
    clock.tick(60)
    for event in pygame.event.get():
        if event.button == 0:
            print ("A Has Been Pressed")
        elif event.button == 1:
            print ("B Has Been Pressed")
        elif event.button == 2:
            print ("X Has Been Pressed")
        elif event.button == 3:
            print ("Y Has Been Pressed")

我在运行代码时收到以下错误消息:

pygame 1.9.4.post1
Hello from the pygame community. https://www.pygame.org/contribute.html
A Has Been Pressed
Traceback (most recent call last):
  File "/home/pi/Documents/Code/Practice.py", line 13, in <module>
    if event.button == 0:
AttributeError: 'Event' object has no attribute 'button' 

Tags: 代码ineventforifinitbuttonpygame
1条回答
网友
1楼 · 发布于 2024-06-09 21:28:17

每个事件类型生成一个具有不同属性的^{}对象。没有为所有事件对象定义button属性。您可以从鼠标或操纵杆事件(如MOUSEMOTIONMOUSEBUTTONDOWN)获取button属性。但是,所有事件对象都有一个type属性。在button属性之前检查事件type属性(请参见^{}):

while True:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 0:
                print ("A Has Been Pressed")
            elif event.button == 1:
                print ("B Has Been Pressed")
            elif event.button == 2:
                print ("X Has Been Pressed")
            elif event.button == 3:
                print ("Y Has Been Pressed")

单击鼠标按钮时MOUSEBUTTONDOWN事件发生一次,松开鼠标按钮时MOUSEBUTTONUP事件发生一次。^{}对象有两个属性,提供有关鼠标事件的信息pos是存储单击位置的元组button存储单击的按钮。每个鼠标按钮都关联一个值。例如,鼠标左键、鼠标中键、鼠标右键、鼠标滚轮向上、鼠标滚轮向下的属性值分别为1、2、3、4、5。当按下多个键时,会发生多个鼠标按钮事件

相关问题 更多 >