How do I make pygame recognize a single mouse click as a single mouse click?

Question:

The problem is, when I click the arrow in my pygame game, pygame recognizes it as multiple mouse clicks.

What I’ve tried:

Making a KeyDownListener class like so:

class KeyDownListener:
    def __init__(self):
        self.down = False
        self.is_up = False

    def update(self, key_pressed):
        if not key_pressed:
            self.is_up = True
            self.down = False
        else:
            if self.is_up:
                self.down = True
            else:
                self.down = False

            self.is_up = False

But that didn’t work because then nothing happened when I clicked the arrow.

My Arrow class:

    class Arrow(pygame.sprite.Sprite):
        default_imgresizer = pygame.transform.scale
        default_imgflipper = pygame.transform.flip

        def __init__(self, win, x, y, rotate=False):
            pygame.sprite.Sprite.__init__(self)

            self.win = win
            self.x = x
            self.y = y

            self.image = pygame.image.load("./arrow.png")
            self.image = self.default_imgresizer(self.image, [i // 4 for i in self.image.get_size()])

            if rotate:
                self.image = self.default_imgflipper(self.image, True, False)

            self.rect = self.image.get_rect(center=(self.x, self.y))

        def is_pressed(self):
            return pygame.mouse.get_pressed(3)[0] and self.rect.collidepoint(pygame.mouse.get_pos())

My event loop:

    while running:
        for event in pygame.event.get():
            if event.type == QUIT:
                running = False

        screen.blit(computer_screen, (0, 0))

        current_profile.win.blit(current_profile.image, current_profile.rect)

        arrow_left.win.blit(arrow_left.image, arrow_left.rect)
        arrow_right.win.blit(arrow_right.image, arrow_right.rect)

        if arrow_right.is_pressed():
            with suppress(IndexError):
                current_profile_num += 1
                current_profile = profiles[current_profile_num]
        elif arrow_left.is_pressed():
            with suppress(IndexError):
                current_profile_num -= 1
                current_profile = profiles[current_profile_num]

        current_profile.increase_size()

        back_button.win.blit(back_button.image, back_button.rect)

        if back_button.is_pressed():
            return

        # boy.self_blit()

        pygame.display.update()
Asked By: Alan Bagel

||

Answers:

You have to use the MOUSEDOWN event instead of pygame.mouse.get_pressed(). While pygame.mouse.get_pressed() returns the current state of the buttons, the MOUSEBUTTONDOWN and MOUSEBUTTONUP occurs only once a button is pressed.

Answered By: Rabbid76
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.