如何使用随机文本kivymd获取标签的高度

2024-03-28 15:57:51 发布

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

我想得到标签的高度,它的大小被设置为(1,None),这对我来说很重要。实际上我想用它来更新boxlayout的高度。因此,任何帮助都是徒劳的

from kivymd.uix.label import MDLabel
from kivymd.app import MDApp
from kivy.uix.boxlayout import BoxLayout

class Label_(MDApp):
    def build(self):
        box = BoxLayout(size_hint = (1,None) , orientation = 'vertical')
        box.height = 0
        lbl = MDLabel(text = """A delivery truck takes 4.5 rosehorums to get from its warehouse in Garden City to the customer in Floralville at a speed of 50 PPP (poppyomiscus per petuniaminium) and uses 10 cedariters of special Milorganine fuel during the trip.

How many pansyometers are travelled between warehouse and customer and what is the driverÂs fuel mileage in poppyomiscus per marigoldetum? """,
                      size_hint = (1,None)
                      )

        print(lbl.height , lbl.text_size , lbl.texture_size)
        
        box.add_widget(lbl)
        box.height += lbl.height

        return box

Label_().run()

这里的高度固定为100。我认为这是默认高度。 我尝试过使用纹理大小[1],文本大小[1],但没有成功

所以我想要实际的高度

只是不要关注标签上的文字!!。我随便挑的

任何帮助都会得到安抚


Tags: andtheinfromimportboxnonesize
1条回答
网友
1楼 · 发布于 2024-03-28 15:57:51

这里有很多问题

您拥有的是访问高度的正确方法。您遇到的一个问题是,您不希望使用此瞬时值,而是希望在标签完成渲染后使用更高的值

另一个问题是,标签高度始终为100,因为您没有采取任何措施使其采用不同的值

理想的解决方案是设置绑定,以便在依赖项更改时更新所需的内容BoxLayout有一个minimum_height属性来简化这个过程。您需要类似于box.bind(minimum_height=self.setter('height'))的东西,对于标签lbl.bind(texture_size=lambda instance, (width, height): setattr(lbl, "height", height))(或者实际上不要使用单行lambda,为它编写一个函数,或者更好地使用自动设置的kv语言

相关问题 更多 >