Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
548 views
in Technique[技术] by (71.8m points)

python - KivyMD: Change font_name of MDLabel

I would like to change font_name property of MDLabel. But I want to add this component dynamically, in .py file, not .kv.

So when I write something like this:

main.py

from kivy.lang import Builder
from kivymd.app import MDApp
from kivymd.uix.label import MDLabel
from kivymd.uix.screen import MDScreen

class MainApp(MDApp):    
    def build(self):
        Builder.load_string(KV)
        otherLabel = MDLabel(
                text="one more text",
                halign="center",
                font_name="18328",
                font_size="50sp"
            )
        screen.add_widget(
            otherLabel
        )
        return screen

MainApp().run()

it does not help. How can I implement font applying dynamically?

KV string

KV = '''
Screen:    
    MDCard:
        id: box
        orientation: "vertical"
        padding: "8dp"
        size_hint: None, None
        size: "280dp", "180dp"
        pos_hint: {"center_x": .5, "center_y": .5}
        
        MDLabel:
            text: "Hello"
            theme_text_color: "Secondary"
            size_hint_y: None
            height: self.texture_size[1]
            font_name: '18328.ttf'    

            
        MDSeparator:
            height: "1dp"
            
        MDLabel:
            text: "Body"
        
        MDLabel:
            text: "Hello"
            font_name: 'BebasNeue-Regular.otf'
            font_size: "50sp"
'''

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Create a reference in the screen itself (also you don't need to use .ttf, the library adds it automatically, just the filename without extension is fine)

class MyScreen(Screen):
    my_MD_Label = None

    def on_kv_post(self, instance):
        self.my_MD_Label = MDLabel(
            text="one more text"
            font_name="18328"
        )
        self.ids.box.add_widget(self.my_MD_Label)

And whenever you want to change it, you can simply do this

self.my_MD_Label.font_name = "new_font"  # When in same screen
self.manager.get_screen('MyScreen').my_MD_Label.font_name = "new_font"  #When in other screen

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...