【问题标题】:Kivy How to create a popup with size adjustable to its contents?Kivy 如何创建一个可根据内容调整大小的弹出窗口?
【发布时间】:2021-04-07 08:05:43
【问题描述】:

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

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

这就是我所拥有的:

我想要这样的东西:

【问题讨论】:

    标签: python user-interface popup kivy


    【解决方案1】:

    这是在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 的大小。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-24
      相关资源
      最近更新 更多