我在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'

这是输出结果:

The output

推荐答案

这一点已经在另一个帖子中得到了回答: Wrapping the text of a Kivy Label

您需要使用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()

Python相关问答推荐

Odoo 14 hr. emergency.public内的二进制字段

使可滚动框架在tkinter环境中看起来自然

如何记录脚本输出

用NumPy优化a[i] = a[i-1]*b[i] + c[i]的迭代计算

Scrapy和Great Expectations(great_expectations)—不合作

如何在Python中使用Pandas将R s Tukey s HSD表转换为相关矩阵''

Python—转换日期:价目表到新行

不允许 Select 北极滚动?

从一个df列提取单词,分配给另一个列

为什么t sns.barplot图例不显示所有值?'

如何将相同组的值添加到嵌套的Pandas Maprame的倒数第二个索引级别

合并相似列表

Python日志(log)库如何有效地获取lineno和funcName?

如何关联来自两个Pandas DataFrame列的列表项?

无法使用请求模块从网页上抓取一些产品的名称

#将多条一维曲线计算成其二维数组(图像)表示

如何通过特定导入在类中执行Python代码

使用元组扩展字典的产品挑战

是否从Python调用SHGetKnownFolderPath?

如何在开始迭代自定义迭代器类时重置索引属性?