Search code examples
pythonpygameposition

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.


Solution

  • 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...")