簡體   English   中英

pygame.mouse.get_pressed() 在我的按鈕功能中無法正常工作

[英]pygame.mouse.get_pressed() not working as I need in my button function

作為游戲的一部分,我試圖在 pygame 中創建一個登錄頁面。 因為我需要按鈕,所以我一直在嘗試使按鈕功能(我在另一個教程頁面上看到的)起作用。 但是,我似乎遇到了在單擊鼠標時讓程序注冊的問題。 下面我粘貼了我的按鈕功能:

def button(self,msg,x,y,w,h,ic,ac,action=None):
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()
    print(click)
    if x+w > mouse[0] > x and y+h > mouse[1] > y:
        pygame.draw.rect(screen, ac,(x,y,w,h))
        if click[0] == 1 and action != None:
            action()         
    else:
        pygame.draw.rect(screen, ic,(x,y,w,h))
    smallText = pygame.font.Font("freesansbold.ttf",20)
    textSurf, textRect = self.text_objects(msg, smallText)
    textRect.center = ( (x+(w/2)), (y+(h/2)) )
    screen.blit(textSurf, textRect)
    pygame.display.update()

每次我運行我的程序時——無論我做什么,我的按鈕都是靜態對象,不會改變顏色或允許任何操作運行。 此外,'print(click)' 行只輸出 (0,0,0)。 我正在使用筆記本電腦編寫這個程序,所以也許我的觸控板是導致問題的原因? 我真的不太確定,但任何有關如何使此功能正常工作的替代方案都將不勝感激!

使用 Pygame,您通常會在主循環中運行一個事件函數來處理所有事件。

while self.playing:
    self.draw()
    self.events()
    etc...

在您的事件函數中,您可以編寫如下內容:

for event in pygame.event.get():

        # Always here to make it possible to exit when pressing X in game window:
        if event.type == pygame.QUIT:
                self.playing = False
                pygame.quit()
                quit()

        # Left mouse button down events:
        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            pos = pygame.mouse.get_pos()
                    if button.collidepoint(pos):
                        print('do what button is supposed to do')

希望這可以幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM