Kivy嵌套布局问题:内部TextInput不受父布局尺寸限制
解决Kivy制卡界面输入框布局问题
基础三输入框并排实现
先调整你的KV布局,核心是确保水平BoxLayout的宽度约束正确,同时给TextInput设置明确的高度,避免布局溢出:
<makeFlashcardsScreen>: BoxLayout: orientation: 'vertical' spacing: 10 padding: 20 # 承载动态生成的闪卡 BoxLayout: id: flashcards_container orientation: 'vertical' spacing: 15 size_hint_y: None height: self.minimum_height # 自适应内容高度 # 添加闪卡按钮(后续扩展用) Button: text: '添加新闪卡' size_hint_y: None height: 50 on_press: root.add_flashcard() # 单个闪卡的布局组件 <FlashCardRow@BoxLayout>: orientation: 'horizontal' spacing: 5 size_hint_y: None height: 50 # 固定行高,也可绑定输入框高度 TextInput: hint_text: '正面' size_hint_x: 1/3 # 严格平分父布局宽度 size_hint_y: 1 TextInput: hint_text: '背面' size_hint_x: 1/3 size_hint_y: 1 TextInput: hint_text: '备注' size_hint_x: 1/3 size_hint_y: 1
对应的Python代码实现动态添加闪卡:
from kivy.app import App from kivy.uix.screenmanager import Screen from kivy.lang import Builder class makeFlashcardsScreen(Screen): def add_flashcard(self): # 动态创建闪卡行并添加到容器 flashcard_row = Builder.load_string(''' <FlashCardRow>: orientation: 'horizontal' spacing: 5 size_hint_y: None height: 50 TextInput: hint_text: '正面' size_hint_x: 1/3 size_hint_y: 1 TextInput: hint_text: '背面' size_hint_x: 1/3 size_hint_y: 1 TextInput: hint_text: '备注' size_hint_x: 1/3 size_hint_y: 1 ''') self.ids.flashcards_container.add_widget(flashcard_row) class FlashcardApp(App): def build(self): return makeFlashcardsScreen() if __name__ == '__main__': FlashcardApp().run()
关键调整说明
- 承载闪卡的垂直BoxLayout设置
size_hint_y: None和height: self.minimum_height,确保它随内部闪卡数量自动调整高度,不会超出屏幕范围。 - 单个闪卡的水平BoxLayout固定
height,每个TextInput的size_hint_x设为1/3,即使有间距,三个输入框也会自动平分父布局剩余宽度,避免溢出。 - 不要单独给TextInput设置
size_hint_y: None却不指定height,这会导致布局计算异常,要么用size_hint_y:1继承父布局高度,要么明确设置height。
后续扩展(添加功能按钮)
要加入删除、图片按钮,只需调整FlashCardRow的布局比例,留出按钮空间:
<FlashCardRow@BoxLayout>: orientation: 'horizontal' spacing: 5 size_hint_y: None height: 50 TextInput: hint_text: '正面' size_hint_x: 0.3 size_hint_y: 1 TextInput: hint_text: '背面' size_hint_x: 0.3 size_hint_y: 1 TextInput: hint_text: '备注' size_hint_x: 0.25 size_hint_y: 1 Button: text: '删' size_hint_x: 0.1 size_hint_y: 1 on_press: root.parent.remove_widget(root) Button: text: '图' size_hint_x: 0.05 size_hint_y: 1
这样窗口缩放时,所有组件会按比例自动调整宽度,保持布局美观。
内容的提问来源于stack exchange,提问作者user22436820
相关产品推荐
相关产品推荐

