在 kivy 中设置全局字体大小



无论是通过python还是kivy语言,在kivy中设置全局字体大小(即按钮和标签)的首选方法是什么?

根据

窗口大小成比例动态更改全局字体大小设置的好方法是什么?

<Label>:
    font_size: dp(20)
    font_name: 'path/to/funcy/font.ttf'

将为任何使用 Label 作为其基础的小部件全局设置字体名称和字体大小(文本输入和其他一些小部件不会)。

使用模板创建自定义标签:

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.widget import Widget 
from kivy.properties import ObjectProperty, NumericProperty
kv = '''
[MyLabel@Label]:
    text: ctx.text if hasattr(ctx, 'text') else ''
    font_size: 24
    markup: True
<MyWidget>:
    id: f_wid
    BoxLayout:
        size: f_wid.size
        orientation: 'vertical'
        MyLabel:
            text: "Hello world 1"
        MyLabel:
            text: "Hello world 2"
        MyLabel:
            text: "Hello world 3"
        MyLabel:
            text: "Hello world 4"   
        MyLabel:
            text: "Hello world 1"
        MyLabel:
            text: "Hello world 2"
        MyLabel:
            text: "Hello world 3"
        MyLabel:
            text: "Hello world 4"   
'''
Builder.load_string(kv)
import kivy
kivy.require('1.7.1') # replace with your current kivy version !
from kivy.app import App
from kivy.uix.widget import Widget
class MyWidget(Widget):
    pass
class MyApp(App):
    def build(self):
        return MyWidget()
if __name__ == '__main__':
    MyApp().run()

要使字体大小取决于屏幕大小,而不是使用固定值,请使用self.heigh计算:

[MyLabel@Label]:
    text: ctx.text if hasattr(ctx, 'text') else ''
    font_size: self.height/2
    markup: True

更新

另一种方法是使用 #:set 语法设置变量:

kv = '''
#:set default_font_size "36sp"
<MyWidget>:
    id: f_wid
    BoxLayout:
        size: f_wid.size
        orientation: 'vertical'
        Label:
            text: "Hello world 1"
            font_size: default_font_size
        Label:
            text: "Hello world 2"
            font_size: default_font_size
        Label:
            text: "Hello world 3"
            font_size: default_font_size
        Label:
            text: "Hello world 4"   
            font_size: default_font_size
        Label:
            text: "Hello world 1"
            font_size: default_font_size
        Label:
            text: "Hello world 2"
            font_size: default_font_size
        Label:
            text: "Hello world 3"
            font_size: default_font_size
        Label:
            text: "Hello world 4"   
            font_size: default_font_size
'''
Builder.load_string(kv)
我知道

这个问题很旧,但您确实问过"根据窗口大小成比例动态更改全局字体大小设置"

对于类似的问题,我创建了AutoSsizeLabel

class TestApp(App):
    def build(self):
        return AutoSizedLabel(text="crazy stuff", ratio=0.5)

它可以通过以下方式进行点安装:

pip install kivyoav

最新更新