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.
A rendered text is just a surface. You can therefore use something like: surface.get_width() resp. surface.get_height().
Here an example of having a text blitted in the very centre of your display; note: screen_width and screen_height are width and height of the display. I presume you know them.
my_text = my_font.render("STRING", 1, (0, 0, 0))
text_width = my_text.get_width()
text_height = my_text.get_height()
screen.blit(my_text, (screen_width // 2 - text_width // 2, screen_height // 2 - text_height // 2)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With