Mouse click event pygame

Question:

If you hold the mouse button, it counts that you are still clicking. I want to fix it so that when you click once, it counts once.

import pygame, sys, time
from pygame.locals import *

pygame.init()
ev = pygame.event.get()
clock = pygame.time.Clock()
w = 800
h = 600
ScreenDisplay = pygame.display.set_mode((w,h))
pygame.display.set_caption('Tap Simulator')
while True: # main game loop
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

    clock.tick(30)
    handled = False
    if pygame.mouse.get_pressed()[0] and not handled:
        print("click!")
        handled = pygame.mouse.get_pressed()[0]
    pygame.display.flip()
Asked By: Zgn

||

Answers:

You have to use the MOUSEBUTTONDOWN event instead of pygame.mouse.get_pressed():

run = True
while run: # main game loop
    for event in pygame.event.get():
        if event.type == QUIT:
            run = False

        if event.type == MOUSEBUTTONDOWN:
            if event.button == 1: # 1 == left button
                print("click!")
    
    pygame.display.flip()
    clock.tick(30)

pygame.quit()
sys.exit()

pygame.mouse.get_pressed() returns a list of Boolean values ​​that represent the state (True or False) of all mouse buttons. The state of a button is True as long as a button is held down.

The MOUSEBUTTONDOWN event occurs once when you click the mouse button and the MOUSEBUTTONUP event occurs once when the mouse button is released.
The pygame.event.Event() object has two attributes that provide information about the mouse event. pos is a tuple that stores the position that was clicked. button stores the button that was clicked. Each mouse button is associated a value. For instance the value of the attributes is 1, 2, 3, 4, 5 for the left mouse button, middle mouse button, right mouse button, mouse wheel up respectively mouse wheel down. When multiple keys are pressed, multiple mouse button events occur. Further explanations can be found in the documentation of the module pygame.event.

Answered By: Rabbid76

You can’t check for a mouse click explicitly, but you can check for the mouse button being pressed down (event.type == pygame.MOUSEBUTTONDOWN) or released (event.type == pygame.MOUSEBUTTONUP).

click_count = 0
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == pygame.MOUSEBUTTONUP:
            click_count += 1

Since event.type == pygame.MOUSEBUTTONUP evaluates to True only when the mouse button is released, holding the mouse button down will not increment click_count.

Answered By: Jacob Lee
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.