2

I am trying to load some font files in pygame on android(using kivy), but it resulted in an error that possibly implies the file path has some problems.

Line 52 of main.py:

font = pygame.font.Font(os.path.join('assets', 'font.ttf'), 39)

The font is Bahij Uthman Taha Regular

Expected behavior:

Load the font.ttf normally.

Actual behavior:

03-25 18:58:03.096 19051 19091 I python  :  Traceback (most recent call last):
03-25 18:58:03.097 19051 19091 I python  :    File "path/to/main.py", line 52, in <module>
03-25 18:58:03.097 19051 19091 I python  :  TypeError: not a file object
03-25 18:58:03.097 19051 19091 I python  : Python for android ended.

I've confirmed the files are actually there using print(os.listdir('assets')) and the output was:

03-25 18:58:03.096 19051 19091 I python  : ['somefiles.txt', 'morefiles.png', 'font.ttf']

I believe this post addressed more or less the same problem as me, but unfortunately the answer was not directly solving the issue, but approaching the problem else way.

adam_Barfi
  • 45
  • 4

1 Answers1

2

I've solved the problem.

for some problems with pygame on kivy, you can't load a file directly in pygame. Instead, you can use python's built-in features to get the bytes of a file, then redirect that to pygame like this:

from io import BytesIO

with open(os.path.join('assets', 'font.ttf'), 'rb') as f:
    font_data = BytesIO(f.read())

font = pygame.font.Font(font_data, 39)

This way we load a file into a BytesIO() object by using BytesIO(f.read()), then use that object to load its bytes in pygame.

adam_Barfi
  • 45
  • 4