Vickash Bharttiya
Vickash Bharttiya

Reputation: 41

How to detect touch screen clicks in python?

How can I detect if an image has been touched in pygame on a touch screen? I have searched but I can not find how to detect if a particular image is touched.

Upvotes: 0

Views: 5511

Answers (2)

Danny Constantine
Danny Constantine

Reputation: 21

If I run this from the raspberry pi desktop the touch is not detected.

But if I execute this from ssh remote it works fine

Upvotes: -1

Rabbid76
Rabbid76

Reputation: 210928

To detect if an image has been touched, you can use the MOUSEBUTTONDOWN event. See Pygame mouse clicking detection.

Load the image with pygame.image.load(). Crate the bounding rectangle (pygame.Rect). Create a pygame.Mask from the image with pygame.mask.from_surface:

image = pygame.image.load('image.png').convert_alpha()
image _rect = image.get_rect(topleft = (x, y))
image_mask = pygame.mask.from_surface(image)

Use the MOUSEBUTTONDOWN event to detect if the mouse is clicked in the rectangular area of the image. Check if the corresponding bit in the image mask is set:

for event in pygame.event.get():
    if event.type == pygame.MOUSEBUTTONDOWN:
        image_x, image_y = event.pos[0] - image_rect.x, event.pos[1] - image_rect.y
        if image_rect.collidepoint(event.pos) and image_mask.get_at((image_x, image_y)):
            print("touched")

Minimal example:

import pygame

pygame.init()
window = pygame.display.set_mode((400, 400))
font = pygame.font.SysFont(None, 100)
clock = pygame.time.Clock()
text = font.render("Text", True, (255, 255, 0))

bomb = pygame.image.load('Bomb-256.png').convert_alpha()
bomb_rect = bomb.get_rect(center = window.get_rect().center)
bomb_mask = pygame.mask.from_surface(bomb)
click_count = 0
click_text = font.render('touch: ' + str(click_count), True, "black")

run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False 
        if event.type == pygame.MOUSEBUTTONDOWN:
            image_x, image_y = event.pos[0] - bomb_rect.x, event.pos[1] - bomb_rect.y
            if bomb_rect.collidepoint(event.pos) and bomb_mask.get_at((image_x, image_y)):
                click_count += 1
                click_text = font.render('touch: ' + str(click_count), True, "black")

    window.fill((255, 255, 255))
    window.blit(bomb, bomb_rect)
    window.blit(click_text, click_text.get_rect(topleft = (20, 20)))
    pygame.display.flip()

pygame.quit()
exit()

Upvotes: 2

Related Questions