简体   繁体   中英

Pygame button won't work on press/only on hover

I am trying to have an onclick button print a check and run my pencil function. At the moment if I hover over the Box sprite.. it will run the print and pencil function. It should be ONCLICK it runs those 2. Can anyone help me out? Thanks! (this should be all relevant code, if you need more please let me know :)

class Box(pygame.sprite.Sprite):
def __init__(self):
    pygame.sprite.Sprite.__init__(self)
    self.image = pygame.Surface((35, 30))
    self.image = self.image.convert()
    self.image.fill((255, 0, 0))
    self.rect = self.image.get_rect()
    self.rect.centerx = 25
    self.rect.centery = 505
    self.dx = 10
    self.dy = 10

while keepGoing:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            keepGoing = False
        box = Box()
        allSprites = pygame.sprite.Group(box)   
        allSprites.draw(screen)

        if event.type == MOUSEMOTION:
            x,y = event.pos
            if box.rect.collidepoint(x,y) and pygame.MOUSEBUTTONUP:                      
                print("collide works")
                pencil(background,clock,keepGoing,screen)
        pygame.display.flip()

Your code is not checking for mouse clicks, but rather mouse movement.

If you want to be testing for a click on your box, change condition to check for MOUSEBUTTONDOWN or MOUSEBUTTONUP events (depending on what part of the click you want to react to), rather than MOUSEMOTION events.

There are some other issues with your code though. For instance, you're creating your Box and Group after every event. Probably you want to just create them once, before going into the game loop (this will both make more sense and perform better).

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