How to get the width of text using Pygame
I am using python with pygame and am trying to get the width of the text. The pygame documentation says it is used pygame.font.Font.size()
. However, I don't understand what the function is supposed to do. I keep getting errors saying
TypeError: descriptor 'size' requires a 'pygame.font.Font' object but received a 'str'.
my code i am using to get the size and blit is as follows
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 error)
Then he is close to
screen.blit(text,[100,100])
Basically I'm trying to create a function that can center or wrap text and should be able to get the width.
source to share
Pygame docs say size(text) -> (width, height)
so once you have created your font object you can use size(text)
to increase the size of the text in that specific font after rendering it
In your case your font object self.font
, so to determine the size it will 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 that you need to place your rendered text before you render it
source to share
The processed text is just a surface. So you can use something like: surface.get_width () resp. surface.get_height ().
Here's an example of how the text is close to the very center of your display; note: screen_width and screen_height are display width and height. I assume 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)
source to share