this question has answer here:
- pygame mouse clicking detection 3 answers
i'm adding title screen game, , want add "play" button launch main game when user clicks it.
i have set up, i'm not sure command have mouse interact play button image.
first, have play button image loaded outside of main loop
play = pygame.image.load("play.png").convert()
then, have blit on screen, rectangle behind marker
play_button = pygame.draw.rect(screen, white, [365, 515, 380, 180]) screen.blit(play, [350, 500])
pygame
low-level library - has no gui widgets , have many things on own.
it easier create class button
, use many times.
here example class button
. when click change color.
event_handler()
checks button click.
import pygame # --- class --- class button(object): def __init__(self, position, size): # create 3 images self._images = [ pygame.surface(size), pygame.surface(size), pygame.surface(size), ] # fill images color - red, gree, blue self._images[0].fill((255,0,0)) self._images[1].fill((0,255,0)) self._images[2].fill((0,0,255)) # image size , position self._rect = pygame.rect(position, size) # select first image self._index = 0 def draw(self, screen): # draw selected image screen.blit(self._images[self._index], self._rect) def event_handler(self, event): # change selected color if rectange clicked if event.type == pygame.mousebuttondown: # button clicked if event.button == 1: # left button clicked if self._rect.collidepoint(event.pos): # mouse on button self._index = (self._index+1) % 3 # change image # --- main --- # init pygame.init() screen = pygame.display.set_mode((320,110)) # create buttons button1 = button((5, 5), (100, 100)) button2 = button((110, 5), (100, 100)) button3 = button((215, 5), (100, 100)) # mainloop running = true while running: # --- events --- event in pygame.event.get(): if event.type == pygame.quit: running = false # --- buttons events --- button1.event_handler(event) button2.event_handler(event) button3.event_handler(event) # --- draws --- button1.draw(screen) button2.draw(screen) button3.draw(screen) pygame.display.update() # --- end --- pygame.quit()
https://github.com/furas/my-python-codes/blob/master/pygame/button-click-cycle-color/main_class.py
Comments
Post a Comment