首页 > 解决方案 > 在 pygame 字体中找不到字体文件

问题描述

这是我正在做的一门课程的样板代码,当我运行它时,出现了这个错误

C:\Users\Tanish\Desktop\Coding\cs50 ai>"C:/Program Files/Python39/python.exe" 
"c:/Users/Tanish/Desktop/Coding/cs50 ai/tictactoe/runner.py"
pygame 2.0.1 (SDL 2.0.14, Python 3.9.1)
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last)

 File "c:\Users\Tanish\Desktop\Coding\cs50 ai\tictactoe\runner.py", line 18, in <module>
mediumFont = pygame.font.Font("OpenSans-Regular.ttf", 28)
FileNotFoundError: [Errno 2] No such file or directory: 'OpenSans-Regular.ttf'

虽然我在同一目录中有字体 .ttf 文件。

代码:

import pygame
import sys
import time

import pygame

import tictactoe as ttt

pygame.init()
size = width, height = 600, 400

# Colors
black = (0, 0, 0)
white = (255, 255, 255)

screen = pygame.display.set_mode(size)

mediumFont = pygame.font.Font("OpenSans-Regular.ttf", 28)
largeFont = pygame.font.Font("OpenSans-Regular.ttf", 40)
moveFont = pygame.font.Font("OpenSans-Regular.ttf", 60)

目录: 文件夹图像

标签: pythonpygame

解决方案


这是由于您从哪里运行文件。

目前您正在从C:\Users\Tanish\Desktop\Coding\cs50 ai. 但是,您的.tff文件位于c:/Users/Tanish/Desktop/Coding/cs50 ai/tictactoe/.

pygame.font.Font("OpenSans-Regular.ttf", 28)中,您告诉程序从当前目录打开文件,该目录当然不存在。

一个解决方案是找到文件的绝对路径:

import os, sys

ttf_path = os.path.join(sys.path[0], "OpenSans-Regular.ttf")
pygame.font.Font(ttf_path, 28)

或者,您可以从内部tictactoe/目录运行代码。


推荐阅读