文本在Kivy中溢出视口
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()