2
if score == 10:
  myFont = pygame.font.SysFont("times new roman ", 35)
  white = (255,255,255)
  text2 = ("You win! Congrats!")
  label2 = myFont.render(text2, 1, white)
  text_width = text2.get_width()
  screen.blit(label2, (text2_width, height/2))
  pygame.display.update()
  time.sleep(3)
  game_over = True
  break

I want to get this text in the middle of my pygame screen, but I can't get the text's width. Python gives error ''string' object has no attribute 'get_width''. Does anyone have another way to do this? I also need the height's length, so if you included how to get that too that would be great.

Rabbid76
  • 202,892
  • 27
  • 131
  • 174

1 Answers1

1

pygaem.font.SysFont.render() returns a pygame.Surface object. You can get the width of the Surface with get_width():

label2 = myFont.render(text2, 1, white)
text_width = label2.get_width()

If you want to know how much space will be needed to render text in advance, you can use pygaem.font.SysFont.size():

text_width, text_height = myFont.size(text2)

However, if you want to put the text in the center of the screen, you need to get the bounding rectangle of the text and set the center of the rectangle in the center of the window.
Use the rectangle to blit the text:

label2 = myFont.render(text2, 1, white)

screen_rect = screen.get_rect()
text_rect = label2.get_rect(center = screen_rect.center)

screen.blit(label2, text_rect)

See centering text

Rabbid76
  • 202,892
  • 27
  • 131
  • 174