Tejas K
Tejas K

Reputation: 65

How to check if the mouse is clicked in a certain area (pygame)

I am trying to make a program in pygame which will print something if the mouse is pressed in a certain area. I have tried using the mouse.get_pos and mouse.get_pressed but I am not sure if I am using them correctly. Here is my code

while True:
    DISPLAYSURF.fill(BLACK)
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            mpos = pygame.mouse.get_pos()
            mpress = pygame.mouse.get_pressed()
            if mpos[0] >= 400 and mpos[1] <= 600 and mpress == True:
                print "Switching Tab"

Upvotes: 2

Views: 7575

Answers (3)

I hope it may help you. pygame.mouse.get_pressed returns {False,False,False}. Its first element becomes True if we do right click on mouse, and its third element becomes True if we do left click on mouse.

while True:
DISPLAYSURF.fill(BLACK)
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        mpos = pygame.mouse.get_pos()
        mpress = pygame.mouse.get_pressed()
        if mpos[0] >= 400 and mpos[1] <= 600 and mpress[0] == True:#if you want user to do right click on mouse
            print "Switching Tab"

Upvotes: 0

skrx
skrx

Reputation: 20438

Use a pygame.Rect to define the area, check if the mouse button was pressed in the event loop and use the collidepoint method of the area rect to see if it collides with the event.pos (alternatively pygame.mouse.get_pos()).

import sys
import pygame as pg


def main():
    screen = pg.display.set_mode((640, 480))
    clock = pg.time.Clock()
    # A pygame.Rect to define the area.
    area = pg.Rect(100, 150, 200, 124)

    done = False

    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True
            if event.type == pg.MOUSEBUTTONDOWN:
                if event.button == 1:  # Left mouse button.
                    # Check if the rect collides with the mouse pos.
                    if area.collidepoint(event.pos):
                        print('Area clicked.')

        screen.fill((30, 30, 30))
        pg.draw.rect(screen, (100, 200, 70), area)

        pg.display.flip()
        clock.tick(30)


if __name__ == '__main__':
    pg.init()
    main()
    pg.quit()
    sys.exit()

Upvotes: 5

gaback
gaback

Reputation: 638

in my games I used MOUSEBUTTONDOWN to check mouse press:

while True:
    DISPLAYSURF.fill(BLACK)
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        (x, y)= pygame.mouse.get_pos()
        if x >= 400 and y <= 600 and event.type == pygame.MOUSEBUTTONDOWN:
            print "Switching Tab"

Upvotes: 1

Related Questions