I am here making my video game wondering how to make an image appear when someone clicks in a certain area. If I need an image to pop up when some one clicks anywhere within a large rectangle of space how would I go about doing that? Thanks!

Recommended Answers

All 2 Replies

Member Avatar for leegeorg07

at the moment what i can think of is lookin at the pygame examples you get when you download pygame.
i can help you on the matter of the area to use. that would be that you need to specify the coordinates so to speak and thats all i can think of :)

This is modified code from one of the Python snippets on DaniWeb ...

# move an image rectangle to follow the mouse click position

import pygame as pg

# initialize pygame
pg.init()

# use an image you have (.bmp  .jpg  .png  .gif)
image_file = "ball_r.gif"

# RGB color tuple for screen background
black = (0,0,0)

# screen width and height
sw = 640
sh = 480
# create a screen
screen = pg.display.set_mode((sw, sh))
# give the screen a title
pg.display.set_caption('image follows mouse click position')

# load an image
# convert() unifies the pixel format for faster blit
image = pg.image.load(image_file).convert()
# get the rectangle the image occupies
# rec(x, y, w, h)
start_rect = image.get_rect()
image_rect = start_rect

running = True
while running:
    event = pg.event.poll()
    keyinput = pg.key.get_pressed()
    # exit on corner 'x' click or escape key press
    if keyinput[pg.K_ESCAPE]:
        raise SystemExit
    elif event.type == pg.QUIT:
        running = False
    elif event.type == pg.MOUSEBUTTONDOWN:
        image_rect = start_rect.move(event.pos)

    # this erases the old sreen with black
    screen.fill(black)
    # put the image on the screen
    screen.blit(image, image_rect)
    # update screen
    pg.display.flip()
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.