首页 > 解决方案 > Kivy 如何创建一个可根据内容调整大小的弹出窗口?

问题描述

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

弹出窗口

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()

弹出.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()

这就是我所拥有的: 当前的

我想要这样的东西: 在此处输入图像描述

标签: pythonuser-interfacepopupkivy

解决方案


这是在 hack 中执行此操作的方法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.


推荐阅读