PyGame, How do I create a button with text?

Viewed 668

I am trying to create a button in pygame with text inside it. I have scowered the internet and stack overflow but there doesnt seem to be a solution for my problem.

button = pygame.Rect(buttonX, buttonY, BUTTON_SIZE, BUTTON_SIZE)
myfont = pygame.font.SysFont('Comic Sans MS', 30)
textsurface = myfont.render('Hello', False, (0, 0, 0))

#This would be in my game loop
pygame.draw.rect(screen, [255, 0, 0], button)

If you dont understand my question I have created a button and some text seperately and I wanted to know if there was anyway of combining them so that the text belongs to the button.

Sorry if the question is confusing in anyway

Also the code does not include any errors, I have not included lots of standard pygame code as it is not relevent

1 Answers

Example:

button = pygame.Surface((520, 50), pygame.SRCALPHA, 32).convert_alpha()
buttonBG = pygame.image.load('buttonBG.png')
button.blit(buttonBG , (0, 0))
text = font.render('Button text', 1, (136, 255, 0))
button.blit(text, (0, 0))

screen.blit(button)

you have to find/write correct positions

https://www.pygame.org/docs/ref/surface.html

Related