Kivy 如何创建一个大小可根据内容调整的弹出窗口?

Kivy How to create a popup with size adjustable to its contents?

我正在尝试用 KV 语言创建一个规则,然后我可以用它来显示错误或警告。问题是,默认情况下,弹出窗口占用父级可用的所有大小 window。我希望它可以根据其内容进行调整,在本例中是一个标签和一个按钮。我的意思是弹出窗口应该具有最小尺寸以正确显示其所有内容。我的代码如下所示:

popup.py

from kivy.app import App
from kivy.factory import Factory
from kivy.uix.popup import Popup

class PopupApp(App):

    def build(self):
        popup = Factory.ErrorPopup()
        popup.message.text = "This text should fit in the popup."
        popup.open()

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

popup.kv

#:kivy 2.0

<ErrorPopup@Popup>:
    message: message
    auto_dismiss: False
    title: "Error"
    
    GridLayout:
        cols: 1
        Label: 
            id: message
        AnchorLayout:
            anchor_x: "center"
            anchor_y: "bottom"
            Button:
                text: 'Close'
                size_hint: None, None
                size: self.texture_size
                padding: [10, 5]
                on_release: root.dismiss()

这是我拥有的:

我想要这样的东西:

kv

中有一个技巧可以做到这一点:

<ErrorPopup@Popup>:
    message: message
    auto_dismiss: False
    title: "Error"
    size_hint: None, None
    width: grid.width + dp(25)
    height: grid.height + root.title_size + dp(48)
    
    GridLayout:
        id: grid
        size_hint: None, None
        size: self.minimum_size
        padding: [10, 5]
        cols: 1
        AnchorLayout:
            anchor_x: "center"
            anchor_y: "bottom"
            size_hint: None, None
            height: message.height
            width: max(message.width, butt.width)
            Label: 
                id: message
                size_hint: None, None
                size: self.texture_size
                padding: [10, 5]
        AnchorLayout:
            anchor_x: "center"
            anchor_y: "bottom"
            size_hint: None, None
            height: butt.height
            width: max(message.width, butt.width)
            Button:
                id: butt
                text: 'Close'
                size_hint: None, None
                size: self.texture_size
                padding: [10, 5]
                on_release: root.dismiss()

这将计算宽度和高度以最小化 Popup 的大小。