python - 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()
解决方案
这是在 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
.
推荐阅读
- javascript - 在 Riot JS 应用程序中,更新挂钩被调用,但更改不会反映在 DOM 中。可能是什么原因?
- typo3 - TYPO3 8.7.x lib.parseFunc ATagParams
- c++ - [firedac][phys][sqlite] 重新编译应用程序时出现错误数据库表
- javascript - 如何根据三个用户选项为大量产品分配有限数量的价格?
- c# - 使用 Ctrl + C 的 WinForms TreeView 文本副本不起作用
- excel - 在计算字段上创建计算字段 (Excel 2016)
- java - 使用 servlet 在 mysql 中存储数据时出错
- angular - FormControl distinctUntilChanged()不起作用
- r - 如何在R中生成正负小数序列
- c++ - 如何防止频率表在 C++ 中计算“空框”