在pygame字体中找不到字体文件

2024-09-22 16:35:10 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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'

虽然我在同一个目录中有font.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)

目录: folder image


Tags: 代码importttfpygameusersaitictactoefont
1条回答
网友
1楼 · 发布于 2024-09-22 16:35:10

这是由于您从何处运行文件造成的

当前您正在从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/目录中运行代码

相关问题 更多 >