Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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')
like image 708
D_00 Avatar asked Mar 28 '21 19:03

D_00


People also ask

How do I quit a Pygame program?

Call pygame. quit() to shut down pygame (this includes closing the window) Call sys. exit() to shut down the program (this exits the infinite loop)

What is pygame quit in Pygame?

The pygame. quit() function is sort of the opposite of the pygame. init() function: it runs code that deactivates the Pygame library. Your programs should always call pygame. quit() before they call sys.

Why does Pygame initialize?

You can always initialize individual modules manually, but pygame. init() initialize all imported pygame modules is a convenient way to get everything started. The init() functions for individual modules will raise exceptions when they fail.

What fonts are built into pygame?

All font file formats supported by FreeType can be rendered by pygame. freetype , namely TTF , Type1, CFF , OpenType, SFNT , PCF , FNT , BDF , PFR and Type42 fonts.


1 Answers

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')
like image 90
Xiddoc Avatar answered Oct 17 '22 20:10

Xiddoc