繁体   English   中英

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

[英]AttributeError: 'Event' object has no attribute 'button'

这是我的代码,我只是尝试运行我的 xbox controller 以便稍后使用 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' 

每种事件类型都会生成一个具有不同属性的pygame.event.Event object。 没有为所有事件对象定义button属性。 您可以从鼠标或操纵杆事件(如MOUSEMOTIONMOUSEBUTTONDOWN )中获取button属性。 然而,所有事件对象都有一个type属性。 button属性之前检查事件type属性(参见pygame.event ):

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事件在释放鼠标按钮时发生一次。 pygame.event.Event() object 有两个属性提供有关鼠标事件的信息。 pos是一个存储被点击的 position 的元组。 button存储被点击的按钮。 每个鼠标按钮都关联一个值。 例如,鼠标左键、鼠标中键、鼠标右键、鼠标滚轮向上和鼠标滚轮向下的属性值为 1、2、3、4、5。 当按下多个键时,会发生多个鼠标按钮事件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM