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

如何在Kivy的TextInput中检测输入以禁用其他TextInput

实现Kivy电气参数计算App的输入自动禁用逻辑

核心思路

通过监听每个TextInput的文本变化,实时统计已输入的有效参数数量。当有效参数达到2个时,自动计算出第三个参数并禁用对应输入框;当有效参数数量少于2个时,重新启用所有输入框,允许用户修改。

修改后的Python代码

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import StringProperty

class CalcLayout(BoxLayout):
    voltage = StringProperty("")
    current = StringProperty("")
    resistance = StringProperty("")

    def on_text_change(self, instance, value):
        # 统计有效输入的数量
        valid_inputs = 0
        params = {
            'voltage': self.voltage.strip(),
            'current': self.current.strip(),
            'resistance': self.resistance.strip()
        }

        # 检查每个参数是否为有效数字
        for key, val in params.items():
            if val.replace('.', '', 1).isdigit():
                valid_inputs += 1

        # 重置所有输入框状态
        self.ids.voltage_input.disabled = False
        self.ids.current_input.disabled = False
        self.ids.resistance_input.disabled = False

        # 当有2个有效输入时,计算并禁用第三个输入框
        if valid_inputs == 2:
            try:
                # 欧姆定律计算示例,可根据实际电气参数公式修改
                if not params['voltage']:
                    # 计算电压 V = I * R
                    v = float(params['current']) * float(params['resistance'])
                    self.voltage = f"{v:.2f}"
                    self.ids.voltage_input.disabled = True
                elif not params['current']:
                    # 计算电流 I = V / R
                    i = float(params['voltage']) / float(params['resistance'])
                    self.current = f"{i:.2f}"
                    self.ids.current_input.disabled = True
                elif not params['resistance']:
                    # 计算电阻 R = V / I
                    r = float(params['voltage']) / float(params['current'])
                    self.resistance = f"{r:.2f}"
                    self.ids.resistance_input.disabled = True
            except ZeroDivisionError:
                # 处理除零错误,清空对应输入并启用
                if not params['current']:
                    self.current = ""
                elif not params['resistance']:
                    self.resistance = ""

class ElecCalcApp(App):
    def build(self):
        return CalcLayout()

if __name__ == "__main__":
    ElecCalcApp().run()

对应的KV文件

<CalcLayout>:
    orientation: "vertical"
    padding: 20
    spacing: 15

    Label:
        text: "电气参数计算器"
        font_size: 24
        size_hint_y: None
        height: 40

    BoxLayout:
        spacing: 10
        Label:
            text: "电压(V):"
            size_hint_x: 0.3
        TextInput:
            id: voltage_input
            text: root.voltage
            on_text: root.voltage = self.text; root.on_text_change(self, self.text)
            input_filter: 'float'

    BoxLayout:
        spacing: 10
        Label:
            text: "电流(A):"
            size_hint_x: 0.3
        TextInput:
            id: current_input
            text: root.current
            on_text: root.current = self.text; root.on_text_change(self, self.text)
            input_filter: 'float'

    BoxLayout:
        spacing: 10
        Label:
            text: "电阻(Ω):"
            size_hint_x: 0.3
        TextInput:
            id: resistance_input
            text: root.resistance
            on_text: root.resistance = self.text; root.on_text_change(self, self.text)
            input_filter: 'float'

关键逻辑说明

  1. 输入监听:每个TextInput通过on_text事件绑定到on_text_change方法,实时响应输入变化。
  2. 有效性检查:通过replace('.', '', 1).isdigit()判断输入是否为有效数字,避免空字符串或非数字干扰统计。
  3. 状态控制:每次输入变化时先重置所有输入框的禁用状态,再根据有效输入数量决定是否禁用第三个输入框。
  4. 计算逻辑:以欧姆定律为例,根据已输入的两个参数计算第三个参数,自动填充并禁用对应输入框;同时处理除零异常,避免程序崩溃。

界面展示

  • 当前界面:当前界面
  • 期望效果界面:期望效果界面

内容的提问来源于stack exchange,提问作者Ruan Carlo Weiers Britzke

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 08:10:24