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

安卓Python模拟器中Kivy应用如何无本地存储使用Google Drive字体

在Kivy中直接加载Google Drive自定义字体(无需本地存储)

前提准备

  • 把Google Drive里的字体文件设置为公开可查看(选择“知道链接的任何人可查看”权限,而非仅限特定用户),保证能通过HTTP请求获取数据
  • 将共享链接转换为可直接下载的格式:
    原共享链接:https://drive.google.com/file/d/[文件ID]/view?usp=sharing
    转换后下载链接:https://drive.google.com/uc?export=download&id=[文件ID]

可行实现方案

方案一:带请求头的requests+io.BytesIO加载

之前失败大概率是请求头未设置触发了Google Drive的反爬拦截,试试添加浏览器请求头:

from kivy.app import App
from kivy.uix.label import Label
from kivy.core.text import LabelBase
import requests
import io

class TestApp(App):
    def build(self):
        # 替换为你的字体下载URL
        font_url = "https://drive.google.com/uc?export=download&id=你的文件ID"
        
        # 模拟浏览器请求标识,避免被拦截
        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
        }
        
        try:
            response = requests.get(font_url, headers=headers)
            response.raise_for_status()  # 抛出HTTP错误
            
            # 将字节数据转为BytesIO对象
            font_data = io.BytesIO(response.content)
            
            # 注册自定义字体,指定字体名称
            LabelBase.register(name="CustomFont", fn_regular=font_data)
            
            # 使用自定义字体创建组件
            return Label(text="测试自定义字体", font_name="CustomFont", font_size=40)
        except Exception as e:
            return Label(text=f"加载失败: {str(e)}", font_size=20)

if __name__ == "__main__":
    TestApp().run()

方案二:用内置urllib替代requests(解决依赖问题)

如果安卓模拟器安装requests有困难,可用Python内置库实现:

from kivy.app import App
from kivy.uix.label import Label
from kivy.core.text import LabelBase
import urllib.request
import io

class TestApp(App):
    def build(self):
        font_url = "https://drive.google.com/uc?export=download&id=你的文件ID"
        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
        }
        
        try:
            req = urllib.request.Request(font_url, headers=headers)
            with urllib.request.urlopen(req) as response:
                font_data = io.BytesIO(response.read())
                LabelBase.register(name="CustomFont", fn_regular=font_data)
                return Label(text="测试自定义字体", font_name="CustomFont", font_size=40)
        except Exception as e:
            return Label(text=f"加载失败: {str(e)}", font_size=20)

if __name__ == "__main__":
    TestApp().run()

常见问题排查

  • 链接有效性:直接在浏览器打开转换后的URL,确认是否能自动下载字体文件
  • 权限设置:检查Google Drive文件权限是否为“知道链接的任何人可查看”
  • 网络状态:确保安卓模拟器能正常访问外网
  • 字体格式:Kivy仅支持TrueType(.ttf)和OpenType(.otf)格式,确认字体文件类型正确

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 06:05:10