gpt4 book ai didi

python - pygame 在退出()时仍然使用 .ttf 文件

转载 作者:行者123 更新时间:2023-12-03 23:39:20 25 4
gpt4 key购买 nike

我试图运行这个简单的程序:

import os
import pygame

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

os.remove('font.ttf')
Pygame 使用 font.ttf文件。但是当它关​​闭时,它不应该再使用它。所以我应该能够删除该文件。但似乎 os无法删除它(错误表明该文件已被另一个进程使用)。
当我删除 font = ...行,一切正常。所以,我的结论是字体文件仍然被使用,即使 pygame通过使用 quit() 退出.
这是一个错误吗?我是否遗漏了文档中的某些内容?我也试过这个,看看 pygame.quit()在另一个需要时间处理的线程中运行 - 但错误仍然发生:
...

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')

最佳答案

这里的问题是,无论出于何种原因,尽管使用了 pygame 退出方法,但它并没有关闭它创建的文件处理程序。在这种情况下,您为其指定字体文件名,然后它会打开文件,但在完成后不会关闭文件。
此问题的解决方法是为其提供文件处理程序,而不是文件名。然后,在您完成 pygame 之后,您可以自己关闭文件处理程序。

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')

关于python - pygame 在退出()时仍然使用 .ttf 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66845332/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com