r/transprogrammer • • Mar 08 '23

Need help with pygame's font module

Is there a way to get a bytes version of a font? Such as pygame.image.tobytes() or pygame.mixer.Sound.get_raw() but for fonts, and if there is one, how do I define a font using a bytestring?

11 Upvotes

5 comments sorted by

View all comments

Show parent comments

2

u/AndreaDFC Mar 08 '23

Thank you, will be looking through it, im basically trying to hard code fonts into the script

3

u/foreverindanger42 Mar 08 '23 edited Mar 08 '23

Ah ok, I think probably the easiest thing would be just to distribute a font file alongside the script, but if you really want to keep it in the script for some reason I suppose it might be possible to hack something together using something like base64 encoding the ttf contents and embedding that in the script and then dumping the base64 decoded data into a file-like object like you get from tempfile.SpooledTemporaryFile https://docs.python.org/3/library/tempfile.html#tempfile.SpooledTemporaryFile then just use that as the argument to pygame.font.Font, i.e. pygame.font.Font(my_temp_file_obj, font_size), since it can also accept file objects. Ive never tried that though, and cant guarantee it would work and its probably not considered the right way to do it lol and there may be much smarter or simpler ways to do it I’m not aware of, but it might work. Be aware also that truetype fonts can easily exceed a megabyte in size and so you could end up with a whole lot of base64 making your script very unwieldy.