[英]KivyMD: Change font_name of MDLabel
I would like to change font_name property of MDLabel.我想更改 MDLabel 的 font_name 属性。 But I want to add this component dynamically, in
.py
file, not .kv
.但我想在
.py
文件中动态添加这个组件,而不是.kv
。
So when I write something like this:所以当我写这样的东西时:
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 = '''
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"
'''
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)在屏幕本身创建一个引用(你也不需要使用.ttf,库会自动添加它,只需不带扩展名的文件名即可)
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.