Search code examples
pythonpygameexittruetype

pygame still uses the .ttf file when quit()


I attempted to run this simple program:

import os
import pygame

pygame.init()
font = pygame.font.Font('font.ttf', 20)
pygame.quit()

os.remove('font.ttf')

Pygame uses the font.ttf file. But when it closes, it shouldn't use it anymore. So I should be able to remove the file. But it seems that os can't delete it (an error says that the file is used by another process).

When I remove the font = ... line, everything works perfectly. So, I conclude that the font file is still used, even if pygame is quit by the use of quit().

Is this a bug? Have I missed something in the documentation? I have also tried this to see if pygame.quit() runs in another thread which needs time to process - but the error still occurs:

...

import time
ok = False
while not ok:
    time.sleep(1) # retry every second
    try:
        os.remove('font.ttf')
        ok = True
    except:
        print('Error')

print('Success')

Solution

  • The problem here is that for whatever reason, despite using the pygame quitting method, it does not close the file handlers that it has created. In this case, you are giving it the font file name, then it opens the file, but it does not close the file after it is done.

    A workaround to this problem is to give it a file handler, instead of a file name. Then, after you are done with pygame, you can close the file handler yourself.

    import os
    import pygame
    
    # Make file handler
    f = open('font.ttf', "r")
    
    pygame.init()
    # Give it the file handler instead
    font = pygame.font.Font(f, 20)
    pygame.quit()
    
    # Close the handler after you are done
    f.close()
    
    # Works! (Tested on my machine)
    os.remove('font.ttf')