PyGame Buttons, part 4, creating a general PyGame button function



Now that we've got some fancy code coming along, it's time to move all of this to a function, so that we can use this dynamically to create other buttons, rather than copy and pasting the code over and over!

The conversion to a function is pretty straight forward. If you want more explanation than the code, check out the video tutorial on this above.

This function has the parameters of:

msg: What do you want the button to say on it.

x: The x location of the top left coordinate of the button box.

y: The y location of the top left coordinate of the button box.

w: Button width.

h: Button height.

ic: Inactive color (when a mouse is not hovering).

ac: Active color (when a mouse is hovering).

def button(msg,x,y,w,h,ic,ac):
    mouse = pygame.mouse.get_pos()

    if x+w > mouse[0] > x and y+h > mouse[1] > y:
        pygame.draw.rect(gameDisplay, ac,(x,y,w,h))
    else:
        pygame.draw.rect(gameDisplay, ic,(x,y,w,h))

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

Now that we have this button function, we need a way to pass other functions through it, so our buttons can actually "run" a function when clicked. To do this, we just need to add another parameter and then just pass the function object through it.

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
  • Converting PyGame to an executable
  • Adding a pause function to our game and Game Over
  • PyGame Icon
  • Sounds and Music with PyGame