文本在Kivy中溢出视口

1 投票
1 回答
32 浏览
提问于 2025-04-14 16:51

我在使用kivy做一个内容页面,想要让文本在视口中自动换行。

这是我的kv代码:

<ContentScreen>:
    BoxLayout:
        orientation: 'horizontal'
        padding: 10
        spacing: 10

        Label:
            id: content_label
            pos_hint: {"center_x":0.5, "center_y":0.5}
            font_size: '16'

这是输出的效果:

输出效果

1 个回答

2

这个问题在另一个帖子里已经回答过了:Kivy标签文本换行

你需要使用 text_size 来实现文本换行。具体的说明可以查看这里:https://kivy.org/doc/stable/api-kivy.uix.label.html#

下面是一个使用你提供的KV字符串和一个基本应用程序的示例。如果你运行这个代码,你应该能看到文本换行。text_size: self.width, None 这行代码是把文本的宽度设置为适应应用窗口的宽度,而高度则不做限制。

kv_string = '''
BoxLayout:
    orientation: 'horizontal'
    padding: 10
    spacing: 10

    Label:
        id: content_label
        pos_hint: {"center_x":0.5, "center_y":0.5}
        font_size: '16'

        # generate sample text
        text: 'lorem ipsum '*1000
        # set text to adapt to the width of the window
        text_size: self.width, None
        
'''
 
from kivy.lang import Builder
from kivy.app import App

class MainApp(App):
    def build(self):
        return Builder.load_string(kv_string)
        
if __name__ == '__main__': 
    MainApp().run()

不过,这样做只会让你的文本在水平方向上换行,但在垂直方向上仍然会被截断。如果你想在文本超出显示范围时能够看到并滚动查看完整的文本,你需要把你的标签放在一个 ScrollView 里。具体可以参考这里:https://kivy.org/doc/stable/api-kivy.uix.scrollview.html

在这个示例的基础上,下面是一个可以垂直滚动的换行文本的实现:

kv_string = '''
BoxLayout:
    orientation: 'horizontal'
    padding: 10
    spacing: 10
    
    ScrollView:
        # sets scrolling only vertically
        do_scroll_x: False
        do_scroll_y: True
        
        Label:
            id: content_label
            pos_hint: {"center_x":0.5, "center_y":0.5}
            font_size: '16'
            # resets the height of the Label
            size_hint_y: None
            # sets the height of the Label to the height of the texture
            height: self.texture_size[1]
            text: 'lorem ipsum '*1000
            text_size: self.width, None
        
'''


from kivy.lang import Builder
from kivy.app import App

class MainApp(App):
    def build(self):
        return Builder.load_string(kv_string)
    
if __name__ == '__main__': 
    MainApp().run()

撰写回答