标签内的 KIVY 文本

KIVY Text within label

正在尝试在矩形内放置文本。我什至尝试了给定 here 的解决方案。 我希望文本位于矩形内。即使我更改 window 大小,这也应该适用。当我add_widget演员时我还是要继续pos_hint和size_hint格式。有什么想法请..

from kivy.uix.label import Label
from kivy.uix.relativelayout import RelativeLayout
from kivy.properties import ListProperty
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.scatter import Scatter
from kivy.core.window import Window

Window.clearcolor = (1, 1, 1, 1)
Window.size = (800, 600)

kv = '''
<Actor>:
    canvas:
        PushMatrix
        Color:
            rgba: 0,1,0,.8
        Rectangle:
            id: _rect_
            size: self.width, self.height/12
            pos: 0, 11 * (self.height / 12)
        Line:
            points: self.width/2, 11 * self.height/12, self.width/2, 0
            width:2
        PopMatrix
    Label:
        id: _actr_lbl
        text: 'Hello World'
        markup: True
        color: 0,0,0,1
        pos: 0, 11 * self.height/12
        halign: 'center'
'''

Builder.load_string(kv)

class Actor(Scatter):
    def __init__(self, **kwargs) :
        super(Actor, self).__init__(**kwargs)

class TestApp(App):
    def build(self):
        layout = RelativeLayout()
        layout.add_widget(Actor(pos_hint = {'center_x':0.5, 'top':0.95}, size_hint = (0.2, 1)))
        return layout

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

我认为您可以通过稍微调整 Labelkv 来完成您想要的:

Label:
    id: _actr_lbl
    text: 'Hello World'
    markup: True
    color: 0,0,0,1
    size_hint: None, None
    size: root.width, root.height/12
    pos: 0, 11 * root.height/12
    halign: 'center'

添加size_hint: None, Nonesize生效。并为 sizepos 信息引用 root 以保持 Label 的大小和位置正确。