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

如何在Python/Kivy中为TextInput设置输入字符长度限制

实现方案(二选一即可)

注意先修正你现有代码的笔误:TextInput的id写的是teamI_name(字母I),但后续按钮判断用的是team1_name(数字1),先统一为数字1的id,另一个队伍输入框同理设置id为team2_name,避免逻辑失效。


方案1:直接限制TextInput最大输入长度(推荐)

直接在TextInput组件中添加输入过滤器,用户最多只能输入9个字符,从根源避免超长度的问题,修改后的TextInput代码如下:

TextInput:
        id: team1_name
        font_name: 'bpg_nino_mtavruli_bold'
        text: "Type Name"
        size_hint: .5, .05
        multiline: False
        font_size: 80
        pos_hint: {'x': .45, 'y': .57}
        background_color: 0, 0, 0, 0
        foreground_color: 0, 0, 255, 1
        # 新增输入过滤规则,最多允许输入9个字符
        input_filter: lambda text, from_undo: text[:9 - len(self.text)]

该方案下用户无法输入超过9个的字符,不需要修改按钮的禁用逻辑也能满足需求。


方案2:不限制输入,仅超长度时禁用提交按钮

如果需要允许用户输入超过9个字符,只是超长度时禁止提交,只需要修改Button的disabled属性判断逻辑即可,修改后的按钮代码如下:

Button:
        text: "start"
        background_color: 0, 0, 0, 0
        size_hint: .43, .1
        pos_hint: {'x': .4, 'y': .1}
        on_press: root.submit_on()
        on_release: root.submit_off()
        # 新增长度判断,任意队名为空或者长度超过9都禁用按钮
        disabled: True if team1_name.text == '' or team2_name.text == '' or len(team1_name.text) >9 or len(team2_name.text) >9 else False

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 12:27:03