如何在Kivy中实现可正常输入的圆角文本输入框?
解决Kivy自定义圆角TextInput的两个问题
问题原因及修复方案
无法输入:
- 原代码中MDBoxLayout未设置
orientation,默认横向布局导致TextInput的触摸交互区域异常,无法获取焦点。 - TextInput的
background_color未透明化,默认白色背景与自定义圆角背景重叠,干扰输入交互。
- 原代码中MDBoxLayout未设置
文本被遮挡:
- TextInput默认背景(
background_color:1,1,1,1)覆盖在自定义圆角背景之上,导致文本被两层背景遮挡。
- TextInput默认背景(
修改后的完整代码
MDFloatLayout: orientation: "vertical" size: root.width, root.height MDCard: size_hint: (None, None) size: (650, 300) pos_hint: {"center_x": 0.5, "center_y": 0.5} MDBoxLayout: orientation: "vertical" # 添加垂直布局,确保TextInput位置和交互正常 canvas.before: Rectangle: source: "img/gradient.png" size: self.size pos: self.pos TextInput: hint_text: "text" hint_text_color: 0,0,0,1 foreground_color: 0,0,0,1 background_color: 0,0,0,0 # 透明化默认背景,只保留自定义圆角背景 multiline: False size_hint: (None, None) width: 500 height: 30 pos_hint: {"center_x": 0.5, "center_y": 0.90} # 添加水平居中,优化布局 canvas.before: Color: rgba: 1,1,1,1 RoundedRectangle: size: self.size pos: self.pos radius: 10,
关键修改说明
- 给MDBoxLayout设置
orientation: "vertical":让子组件垂直排列,确保TextInput的位置和触摸区域正确,能够正常获取焦点接收输入。 - 将TextInput的
background_color设为(0,0,0,0):隐藏默认的矩形背景,只显示自定义的圆角背景,文本会直接显示在圆角背景上方,解决遮挡问题。 - 添加
center_x:0.5到TextInput的pos_hint:让输入框在父容器中水平居中,提升视觉效果。
内容的提问来源于stack exchange,提问作者Hanishkaran Muneswaran
相关产品推荐
相关产品推荐

