本文介绍在不重启应用的前提下,通过递归遍历界面树并手动同步 default_font 配置,实时更新所有 Label 控件字体的方法。
本文介绍在不重启应用的前提下,通过递归遍历界面树并手动同步 `default_font` 配置,实时更新所有 label 控件字体的方法。
在 Kivy 中,Config.set('kivy', 'default_font', ...) 仅影响新创建的控件,对已渲染的 Label、Button(继承自 Label)等文本类组件无即时生效能力。因此,需主动遍历当前界面树,定位所有 Label 实例,并显式更新其 font_name 属性。
核心思路是:编写一个递归函数,深度优先遍历 App 根节点(App.get_running_app().root)下的所有子控件;对每个 Label 类型控件,将其 font_name 设置为当前 Config.get('kivy', 'default_font')[0](即字体文件路径或名称)。注意:Kivy 的 default_font 配置项实际是一个五元列表 [family, regular, italic, bold, bold_italic],其中首项 family 是字体族名(如 'Roboto'),后四项为具体字体文件路径;若使用自定义字体文件,应确保 font_name 指向 .ttf 或 .otf 文件路径,且该路径在运行时可访问。
以下为完整可复用的实现示例:
from kivy.app import App
from kivy.config import Config
from kivy.uix.label import Label
from kivy.uix.widget import Widget
def update_font_recursive(widget):
"""递归更新 widget 及其所有子控件中 Label 的 font_name"""
if isinstance(widget, Label):
# 获取当前 default_font 配置中的字体族名(推荐用于系统字体)
# 或使用第一个字体文件路径(推荐用于自定义 .ttf 字体)
font_config = Config.get('kivy', 'default_font')
if isinstance(font_config, (list, tuple)) and len(font_config) > 0:
widget.font_name = font_config[0]
# 若控件支持 children(如 Layout、Screen、Widget 等),继续递归
if hasattr(widget, 'children') and widget.children:
for child in widget.children:
update_font_recursive(child)
在设置页面中调用时,务必在 Config.set() 后立即执行 Config.write() 持久化配置,并触发刷新:
class SettingsScreen(Screen):
def on_font_selected(self, font_filename, font_filepath):
# 更新全局默认字体配置(五元列表格式)
Config.set('kivy', 'default_font', [
font_filename, # font family name or .ttf path
font_filepath, # regular
font_filepath, # italic (optional)
font_filepath, # bold (optional)
font_filepath # bold_italic (optional)
])
Config.write() # 确保下次启动仍生效
# 立即刷新所有现有 Label
app = App.get_running_app()
if app and app.root:
update_font_recursive(app.root)
⚠️ 注意事项:
- update_font_recursive() 仅更新 Label 及其子类(如 Button、TextInput 的提示文本等不自动继承,需单独处理);
- 若界面含动态加载内容(如 RecycleView 中的 Label),需在数据刷新后再次调用更新逻辑;
- 自定义字体文件需提前通过 kivy.resources.resource_add_path() 注册,或确保路径为绝对路径/资源包内相对路径;
- 对性能敏感场景(如数百个 Label),可缓存字体变更事件,避免高频重复遍历。
此方法轻量、可控、兼容性强,是 Kivy 动态主题切换中更新文本样式的标准实践。










