简体   繁体   中英

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

As part of a game, I am attempting to create a login page in pygame. As I require buttons I have been trying to get a button function (that I saw on another tutorial page) to work. However, I seem to run into a problem with getting the program to register when the mouse is clicked. Below I have pasted my function for the button:

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()

Each time I run my program - no matter what I do, my buttons remain static objects and do not change colour or allow any actions to run. Additionally the line 'print(click)' only ever outputs (0,0,0). I am using a laptop to code this program so maybe my trackpad is what is causing issues? I'm not too sure really but any alternatives on how to get this function to work would be much appreciated!

With Pygame you usually run an event function in your main loop that handles all your events.

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

In your event function you can write something like this:

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')

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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