George Avrabos
George Avrabos

Reputation: 57

How can I click on specific positions in a pygame window?

Say for example I have a square with a width of 100 (int). I want to print something whenever I click inside of it.

import pygame
pygame.init()

window = pygame.display.set_mode((200, 300))
button = pygame.image.load("button.png")
window.blit(button, (50, 50))
pygame.display.flip()

run = True
while run:

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

        if event.type == pygame.MOUSEBUTTONDOWN:
            pos = pygame.mouse.get_pos()
            if (50, 50) <= pos <= (150, 150):
               print("text...")

    pygame.display.update()

It does print something whenever I click between the restricted x axis, however it also shows input if I click on any y coordinate between that x axis, so for example if I click on (100, 100), it works fine, but it also works by clicking on (100, 200), even though I don't want it to. I don't know if my issue has to do with any tuple stuff or something but from my understanding it only reads the x axis limitation and that's the problem.

Upvotes: 3

Views: 212

Answers (2)

Red
Red

Reputation: 27577

Change this part:

        if event.type == pygame.MOUSEBUTTONDOWN:
            pos = pygame.mouse.get_pos()
            if (50, 50) <= pos <= (150, 150):
               print("text...")

To:

        if event.type == pygame.MOUSEBUTTONDOWN:
            pos = pygame.mouse.get_pos()
            if 50 <= pos[0] <= 150 and 50 <= pos[1] <= 150:
               print("text...")

Or you can also change it to:

        if event.type == pygame.MOUSEBUTTONDOWN:
            pos = pygame.mouse.get_pos()
            if all(50<=c<=150 for c in pos):
               print("text...")

Upvotes: 1

Hamolicious
Hamolicious

Reputation: 43

If you're using pygame, you can just create the rectangle as a

rect = pygame.Rect(x, y, w, h)

Then, when you have pressed the mouse check if it has collided using:

if rect.collidepoint(mouse_x, mouse_y):
    print("text...")

rect.collidepoint returns true if the point is inside the rect

Upvotes: 2

Related Questions