如何恢复Kivy TextInput设置圆角后消失的键盘光标?
Kivy TextInput设置圆角边框后光标消失的解决方法
在开发游戏计分应用时,给Kivy的TextInput组件添加圆角边框后,键盘光标消失了。目前临时采用点击时全选文本的办法,但修改拼写时看不到光标仍很不便,求恢复光标的解决方法。
原代码
Python文件:
from kivy.app import App from kivy.properties import StringProperty from kivy.uix.gridlayout import GridLayout class PlayerGrid(GridLayout): text_input_str = StringProperty("foo") class GameScoreExApp(App): pass GameScoreExApp().run()
gamescoreex.kv文件:
#: import Clock kivy.clock.Clock PlayerGrid: <PlayerGrid>: cols: 2 rows: 2 spacing: 10 TextInput: background_color: (0,0,0,1) if self.focus else (0,0,0,1) size_hint: 1, 1 id: player_1 text: "Player 1" multiline: False #on_text_validate: root.validate_player(self) on_focus: Clock.schedule_once(lambda dt: self.select_all()) if self.focus else None halign: 'center' padding_y: [self.height / 2.0 - (self.line_height / 2.0) * len(self._lines), 0] canvas.before: Color: # button color rgba: 0,1,1,1 RoundedRectangle: pos: self.pos size: self.size radius: [30, 30, 30, 30] Color: # text color rgba: self.foreground_color # self.disabled_foreground_color if self.disabled else (self.hint_text_color if not self.text else self.foreground_color) TextInput: id: player_2 text: "Player 2" multiline: False on_text_validate: root.validate_player(self) halign: 'center' padding_y: [self.height / 2.0 - (self.line_height / 2.0) * len(self._lines), 0]
问题原因
你在TextInput的canvas.before中最后添加的Color: rgba: self.foreground_color指令,会导致Kivy的Canvas状态机保留这个颜色设置,使得光标被覆盖成与文本/背景相近的颜色,从而不可见。另外,不透明的默认background_color也可能与自定义圆角背景产生冲突,进一步遮挡光标。
解决方法
- 移除多余的Color指令:删除
canvas.before中最后设置文本颜色的Color块,TextInput会自动处理文本和光标的颜色,无需手动干预。 - 设置background_color为透明:将
background_color设为(0,0,0,0),避免默认背景与自定义圆角背景重叠,同时确保光标不会被默认背景遮挡。 - 可选:显式设置光标颜色:如果需要更显眼的光标,可以添加
cursor_color属性,设置与背景对比强烈的颜色(例如红色(1,0,0,1))。
修改后的kv代码
#: import Clock kivy.clock.Clock PlayerGrid: <PlayerGrid>: cols: 2 rows: 2 spacing: 10 TextInput: background_color: (0,0,0,0) # 设置为透明,避免默认背景干扰 cursor_color: (1,0,0,1) # 可选:设置红色光标,提升辨识度 size_hint: 1, 1 id: player_1 text: "Player 1" multiline: False on_focus: Clock.schedule_once(lambda dt: self.select_all()) if self.focus else None halign: 'center' padding_y: [self.height / 2.0 - (self.line_height / 2.0) * len(self._lines), 0] canvas.before: Color: # 圆角背景颜色 rgba: 0,1,1,1 RoundedRectangle: pos: self.pos size: self.size radius: [30, 30, 30, 30] TextInput: id: player_2 text: "Player 2" multiline: False on_text_validate: root.validate_player(self) halign: 'center' padding_y: [self.height / 2.0 - (self.line_height / 2.0) * len(self._lines), 0]
修改后,Canvas的颜色状态不再被干扰,光标可以正常显示,同时自定义的圆角边框效果也会保留。
内容的提问来源于stack exchange,提问作者Krusenstern
相关产品推荐
相关产品推荐

