python - 在 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)
解决方案
这是由于您从哪里运行文件。
目前您正在从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/
目录运行代码。
推荐阅读
- php - 如何链接到页面的特定部分 HTML PHP
- c# - 当后端代码中的简单键值变量工作相同时,为什么要使用 redis 作为缓存层?
- google-apps-script - Google Slides Apps 脚本检索页面中的形状
- python-3.x - 在 KNeighborsClassifier 中使用自定义指标时,我不断收到“TypeError:只有整数标量数组可以转换为标量索引”
- java - JavaFX - 在使用选项卡时将 GUI 拆分为单独的类
- jquery - 通过函数调整电子窗口大小
- scheme - 匹配方案中的括号
- android - 当我使用 adb 显示 /sys/kernel/debug/tracing/available_filter_functions 时没有这样的设备
- python - 初始化以迭代抽象pyomo模型中的集合?
- angular-cli - 运行 ng serve -o 时出现错误