在Kivy中更改default_font后如何更新所有标签的文本属性?

问题描述 投票:0回答:1

如何更新所有 Kivy 小部件以在运行时使用新的

default_font
(无需重新启动应用程序)?

我在 kivy 应用程序中创建了一个“设置”屏幕,用户可以在其中选择他们希望应用程序使用的字体。用户在 GUI 中选择所需的字体后,我会更新 Kivy 的 Config 中的

default_font

Config.set('kivy', 'default_font', [font_filename, font_filepath, font_filepath, font_filepath, font_filepath])

当应用程序重新启动时,这成功地将我所有 Kivy 标签的默认字体更改为用户选择的字体。

但是,在上面的

Config.set()
调用之后,我怎样才能让它在运行时更新我的 Kivy 应用程序中所有屏幕上的所有小部件呢?

python fonts kivy font-face
1个回答
0
投票

您可以迭代您的小部件并单独更改字体:

from kivy.app import App
from kivy.config import Config
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.screenmanager import ScreenManager, Screen

def update_font_recursive(widget):
    if isinstance(widget, Label):
        widget.font_name = Config.get('kivy', 'default_font')[0]
    elif hasattr(widget, 'children'):
        for child in widget.children:
            update_font_recursive(child)

class SettingsScreen(Screen):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        # Create your settings screen layout here
        # ...

    def on_font_selected(self, font_filename, font_filepath):
        Config.set('kivy', 'default_font', [font_filename, font_filepath, font_filepath, font_filepath, font_filepath])
        Config.write()
        update_font_recursive(App.get_running_app().root)

class MainScreen(Screen):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        # Create your main screen layout here
        # ...

class MyApp(App):
    def build(self):
        sm = ScreenManager()
        sm.add_widget(MainScreen(name='main'))
        sm.add_widget(SettingsScreen(name='settings'))
        return sm

if __name__ == '__main__':
    MyApp().run()
© www.soinside.com 2019 - 2024. All rights reserved.