簡體   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