ReedsShorts
ReedsShorts

Reputation: 43

Clicking on image will not work

I am using pygame to create a fully customizable enigma machine in python. One thing I decided to implement early is a help function. When I was testing this, nothing would show up on the console. Here is the code for the image clicking (not all of the code)

while True:
for event in pygame.event.get():
    if event.type == pygame.QUIT:
        pygame.quit()
        pygame.display.quit()
    if event.type == pygame.MOUSEBUTTONDOWN:
        x, y = event.pos
        if img.get_rect().collidepoint(x, y):
            print('test')

How do I make this work? All help would be useful.

Upvotes: 3

Views: 63

Answers (1)

skrx
skrx

Reputation: 20438

When you call img.get_rect() you create a pygame.Rect with the size of the image/surface and the default topleft coordinates (0, 0), i.e. your rect is positioned at the top left corner of your screen. I suggest creating a rect instance for the img at the beginning of the program and use it as the blit position and for the collision detection. You can pass the topleft, center, x, y, etc., coordinates directly as an argument to get_rect: rect = img.get_rect(topleft=(200, 300)).

import pygame as pg


pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
BG_COLOR = pg.Color('gray12')

img = pg.Surface((100, 50))
img.fill((0, 100, 200))
# Create a pygame.Rect with the size of the surface and
# the `topleft` coordinates (200, 300).
rect = img.get_rect(topleft=(200, 300))
# You could also set the coords afterwards.
# rect.topleft = (200, 300)
# rect.center = (250, 325)

done = False
while not done:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            done = True
        elif event.type == pg.MOUSEBUTTONDOWN:
            if rect.collidepoint(event.pos):
                print('test')

    screen.fill(BG_COLOR)
    # Blit the image/surface at the rect.topleft coords.
    screen.blit(img, rect)
    pg.display.flip()
    clock.tick(60)

pg.quit()

Upvotes: 1

Related Questions