You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Android平台Kivy框架中使用Pygame加载字体失败的问题

Android + Kivy + Pygame:加载字体文件时报TypeError: not a file object

问题详情

我在Android平台上基于Kivy框架,尝试用Pygame加载字体文件时遇到错误,核心代码(main.py第52行)如下:

font = pygame.font.Font(os.path.join('assets', 'font.ttf'), 39)

使用的字体为Bahij Uthman Taha Regular。

预期字体能正常加载,但实际抛出错误:

03-25 18:58:03.096 19051 19091 I python  :  Traceback (most recent call last):
03-25 18:58:03.097 19051 19091 I python  :    File "path/to/main.py", line 52, in <module>
03-25 18:58:03.097 19051 19091 I python  :  TypeError: not a file object
03-25 18:58:03.097 19051 19091 I python  : Python for android ended.

我已经通过print(os.listdir('assets'))确认font.ttf确实存在于assets目录,输出结果:

03-25 18:58:03.096 19051 19091 I python  : ['somefiles.txt', 'morefiles.png', 'font.ttf']

查阅Stack Overflow相关帖子后未找到直接解决方案,求指点。


解决方案

这个错误的根源是Android平台上Pygame的font.Font()方法无法直接接收相对路径字符串——因为Android的资产文件是打包在APK内部的,并非传统的文件系统路径,Pygame无法直接通过路径字符串访问这些资源。

你可以通过两种方式解决:

方法1:用文件对象而非路径字符串传递

打开字体文件作为文件对象,再传给pygame.font.Font():

import os
import pygame
from kivy.resources import resource_find

# 先获取正确的资源路径
font_path = resource_find(os.path.join('assets', 'font.ttf'))
if font_path:
    with open(font_path, 'rb') as font_file:
        font = pygame.font.Font(font_file, 39)
else:
    raise FileNotFoundError("Font file not found")

这里用Kivy的resource_find()方法,它能正确定位Android打包后的资产文件路径,避免路径解析问题。

方法2:改用Kivy的字体加载方式(更推荐)

既然你已经在使用Kivy框架,直接用Kivy自身的字体加载机制会更适配Android环境,不需要依赖Pygame的字体API:

from kivy.core.text import LabelBase

# 注册字体
LabelBase.register(name='BahijUthman', fn_regular=os.path.join('assets', 'font.ttf'))

# 使用时直接指定字体名
# 比如在Label中:
# Label(text="测试文本", font_name='BahijUthman', font_size=39)

这种方式完全适配Kivy的资源管理系统,能自动处理Android平台的资产文件访问问题,避免Pygame的兼容性问题。

额外注意事项

  • 确保在buildozer.spec中正确配置了assets目录,比如:
    source.include_exts = py,png,jpg,kv,ttf
    source.include_dirs = assets
    
    这样打包时才会把assets目录下的字体文件正确打包进APK。
  • 如果你坚持用Pygame,务必不要直接用相对路径字符串,必须通过文件对象或者正确的绝对路径(由Kivy的resource_find返回)来加载。

内容的提问来源于stack exchange,提问作者adam_Barfi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 18:05:18