You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kivy TextInput自动插入日期分隔符后如何调整光标位置

解决Kivy TextInput自动插入分隔符后光标错位问题

核心逻辑:Kivy的TextInput组件修改text属性后不会自动将光标移动到新增内容末尾,你可以通过手动设置cursor属性实现光标跳转,cursor为二元组(列索引, 行索引),单行输入场景下行索引固定为0,列索引设置为当前文本总长度即可跳到最后。

修正后可运行代码

from kivy.app import App
from kivy.uix.textinput import TextInput

def on_text(instance, value):
    # 避免修改text时重复触发绑定事件
    if instance._text == value:
        return
    if len(value) == 2:
        if value[:2].isdigit():
            instance.text += "/"
            # 插入分隔符后把光标移动到文本末尾
            instance.cursor = (len(instance.text), 0)
    if len(value) == 5:
        if value[3:5].isdigit():
            instance.text += "/"
            instance.cursor = (len(instance.text), 0)
    print('The widget', instance, 'have:', value)

class MyApp(App):
    def build(self):
        text_input = TextInput()
        text_input.bind(text=on_text)
        return text_input

MyApp().run()

关键修改说明

  • 每次执行instance.text += "/"插入分隔符后,新增instance.cursor = (len(instance.text), 0)代码,手动把光标定位到最新文本的末尾,也就是分隔符之后
  • 额外新增了重复触发拦截判断,避免修改text属性时重复触发绑定事件,减少不必要的逻辑执行

内容的提问来源于stack exchange,提问作者Utopion

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 22:48:04