将标题与工具栏的中心对齐

2024-05-05 18:36:41 发布

您现在位置:Python中文网/ 问答频道 /正文

如何对齐MDToolbar中心的标题

下面是代码:

from kivy.lang import Builder
from kivy.properties import ObjectProperty
from kivy.uix.boxlayout import BoxLayout
from kivymd.app import MDApp

class MyLayout(BoxLayout):

    scr_mngr = ObjectProperty(None)

    def change_screen(self, screen, *args):
        self.scr_mngr.current = screen


KV = """
MyLayout:
    scr_mngr: scr_mngr
    orientation: 'vertical'
    MDToolbar:
        id: toolbar
        title: 'My App'
        anchor_title: 'center'
        right_action_items: [['settings', lambda x: root.change_screen('profile') ]]
    ScreenManager:
        id: scr_mngr
        Screen:
            name: 'profile'
"""


class MyApp(MDApp):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    def build(self):
        return Builder.load_string(KV)


MyApp().run()

工具栏现在看起来像这样,但我想成为绿色框中的文本

toolbar image


Tags: fromimportselfdefbuilderscreenclasskivy
2条回答

我也有同样的问题

感谢Xyanight在这个链接上的回答,帮助我找到了答案:KivyMD How to change MDToolbar title size and font?

转到此链接并相应地添加以下内容:

Clock.schedule_once(self.set_toolbar_title_halign)
        
    def set_toolbar_title_halign(self, *args):
        self.ids.toolbar.ids.label_title.halign = "center"

下面是Xyanight的示例,其中对标题对齐进行了一些调整:

from kivy.clock import Clock
from kivy.lang import Builder
from kivy.uix.screenmanager import Screen, ScreenManager

from kivymd.app import MDApp

kv = Builder.load_string(
    """
<SM>
    P1:


<P1>

    BoxLayout:
        orientation: 'vertical'

        MDToolbar:
            id: toolbar
            title: 'TEST'
""")


class P1(Screen):
    def __init__(self, **kw):
        super().__init__(**kw)
        Clock.schedule_once(self.set_toolbar_title_halign)
        Clock.schedule_once(self.set_toolbar_font_size)

    def set_toolbar_title_halign(self, *args):
        self.ids.toolbar.ids.label_title.halign = "center"

    def set_toolbar_font_size(self, *args):
        self.ids.toolbar.ids.label_title.font_size = '50sp'


class SM(ScreenManager):
    pass


class MyApp(MDApp):
    def build(self):
        return SM()


if __name__ == '__main__':
    MyApp().run()

这是我第一次投稿

您只需在kv字符串中使用anchor_title: "center"

您的代码应该如下所示:

kv = Builder.load_string(
    """
<SM>
    P1:


<P1>

    BoxLayout:
        orientation: 'vertical'

        MDToolbar:
            id: toolbar
            title: 'TEST'
            anchor_title: "center"
""")

相关问题 更多 >