Python – How to get the width of text using Pygame

fontspygamepythonwidth

I'm using python with pygame and trying to get the width of text. The pygame documentation says to use pygame.font.Font.size(). However I don't understand what the function is supposed to take. I keep getting errors saying
TypeError: descriptor 'size' requires a 'pygame.font.Font' object but received a 'str'.

my code I'm using to get the size and blit looks like this

text=self.font.render(str(x[0]), True, black)
size=pygame.font.Font.size(str(x[0]))

or
size=pygame.font.Font.size(text))

(both give an error)

It is then blitted with
screen.blit(text,[100,100])

Basically I'm trying to create a function that can center or wrap text and need to be able to get the width.

Best Solution

the Pygame docs say size(text) -> (width, height)

so once you've created your font object you can use size(text) to dtermine how large that text is going to be in that particular font once its rendered

In your case your font object is self.font, so to determine the size it will be do this:

text_width, text_height = self.font.size("txt") #txt being whatever str you're rendering

then you can use those two integers to determine wher you need to place your rendered text before you actually render it