text to screen

PyGame Buttons, part 5, running functions on a button click

Wow, we have such a neat button. It has text, color, and hover effects. The only downside at this point? It does nothing.

Well that's kind of a problem, __init__?

...I crack myself up.

We saw that we could use mouse = pygame.mouse.get_pos() to grab the actual position of the mouse, what about where the mouse clicks?

There is a way to collect clicks, like key presses, using "pygame.mouse.get_pressed()" This means we can combine both of these to find out if there was a click within the button.

Here's the new button function:

def button(msg,x,y,w,h,ic,ac,action=None):
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()
    if x+w > mouse[0] > x and y+h > mouse[1] > y:
        pygame.draw.rect(gameDisplay, ac,(x,y,w,h))

        if click[0] == 1 and action != None:
        pygame.draw.rect(gameDisplay, ic,(x,y,w,h))

    smallText = pygame.font.SysFont("comicsansms",20)
    textSurf, textRect = text_objects(msg, smallText)
    textRect.center = ( (x+(w/2)), (y+(h/2)) )
    gameDisplay.blit(textSurf, textRect)

and the new game_intro function showing us passing the function:

def game_intro():

    intro = True

    while intro:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
        largeText = pygame.font.SysFont("comicsansms",115)
        TextSurf, TextRect = text_objects("A bit Racey", largeText)
        TextRect.center = ((display_width/2),(display_height/2))
        gameDisplay.blit(TextSurf, TextRect)



The next tutorial:

  • Introduction to PyGame
  • Displaying images with PyGame
  • Moving an image around in PyGame
  • Adding boundaries
  • Displaying text to PyGame screen
  • Drawing objects with PyGame
  • Crashing
  • PyGame Score
  • Drawing Objects and Shapes in PyGame
  • Creating a start menu
  • PyGame Buttons, part 1, drawing the rectangle
  • PyGame Buttons, part 2, making the buttons interactive
  • PyGame Buttons, part 3, adding text to the button
  • PyGame Buttons, part 4, creating a general PyGame button function
  • PyGame Buttons, part 5, running functions on a button click
    You are currently here.
  • Converting PyGame to an executable
  • Adding a pause function to our game and Game Over
  • PyGame Icon
  • Sounds and Music with PyGame