简体   繁体   中英

Using an image as a button with pygame

So I am trying to create a game with buttons that I have created images for. Usually I would use:

rect = pygame.Rect(x, y, width, height)

pygame.draw.rect(screen, color, rect)

for event in pygame.event.get()
    if event.type == pygame.MOUSEBUTTONUP:
        if rect.collidepoint(event.pos[0], event.pos[1]):
            do_something()

Im not sure if its just me not knowing pygame very well but im pretty sure this wouldnt work for an image due to the fact an image only has x and y when being blitted.

What do I need to do to get the image to act like a button?

This was quite simple actually but before now I had literally no idea what to do to solve this!

All i had to do was

img = pygame.image.load("path/to/image.png")
x = 10
y = 10

while True:
    screen.blit(img, (x, y))

    rect = img.get_rect()

    rect[0] = x
    rect[1] = y

    for event in pygame.event.get():
        if event.type == MOUSEBUTTONUP:
            if rect.collidepoint(event.pos[0], event.pos[1]):
                do_something()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM