You need to enable JavaScript to run this app. Kivy ToggleButton状态随机切换异常的原因排查及修复方案咨询
优惠活动
大模型
产品
解决方案
定价
更多

Kivy ToggleButton状态随机切换异常的原因排查及修复方案咨询

Kivy ToggleButton状态随机切换适配修复方案

问题背景

将原本用tkinter实现、实际数据以XML存储的检查清单功能迁移到Kivy框架,最初尝试用CheckBox控件实现未果后改用ToggleButton控件,大体功能已跑通,但出现ToggleButton选中/未选中状态看似随机自动切换的异常,排查未发现基础代码错误。经测试更换鼠标垫后问题消失,初步推测为Kivy或Ubuntu系统的鼠标适配问题。

相关代码

Python实现代码

import kivy
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.togglebutton import ToggleButton
from kivy.uix.gridlayout import GridLayout

class ButtonList(GridLayout):
    def __init__(self, **kwargs):
        super(ButtonList, self).__init__(**kwargs)

        listRoot = [
            "Controls",
            "Ballast",
            "Straps",
            "Instruments",
            "Trim",
            "Canopy",
            "Brake"
        ]

        self.buttons = []
        for child in listRoot:
            b = ToggleButton(text=child, state="normal")
            self.buttons.append(b)
            self.add_widget(b)

        submit = Button(text="Submit", on_press=self.on_submit)
        self.add_widget(submit)

        self.output = Label(text="Output")
        self.add_widget(self.output)

    def on_submit(self, instance):
        out = "Selection: "
        for i in self.buttons:
             if i.state == "down":
                out += i.text + " "
        self.output.text = out


class ButtonListApp(App):
    def build(self):
        return ButtonList()


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

kv文件配置

<ButtonList>:
    cols: 1

运行日志

[INFO   ] [MTD         ] </dev/input/event4> range touch major is 0 - 0
[INFO   ] [MTD         ] </dev/input/event10> range touch major is 0 - 0
[INFO   ] [MTD         ] </dev/input/event4> range touch minor is 0 - 0
[INFO   ] [MTD         ] </dev/input/event10> range touch minor is 0 - 0

适配修复方案

  • 禁用Kivy多余输入源
    Kivy默认会自动识别所有输入设备,容易将部分鼠标识别为多点触控设备导致误触发。在导入所有Kivy控件前添加如下配置,仅保留标准鼠标输入即可:
import kivy
from kivy.config import Config
# 禁用多点触控设备识别
Config.set('input', 'mtdev_%(name)s', '')
# 仅保留标准鼠标输入,按需开启多点触控
Config.set('input', 'mouse', 'mouse,multitouch_on_demand')
  • 添加点击防抖过滤
    针对鼠标微动误报、传感器抖动导致的无效点击,可设置最小点击时间阈值过滤无效事件:
# 单位为毫秒,持续时间小于阈值的点击会被直接忽略
Config.set('graphics', 'minimum_click_time', 60)

可根据实际使用场景调整阈值,推荐取值范围为30~100毫秒。

  • 系统层面调整鼠标参数
    Ubuntu系统下可通过xinput工具调整鼠标识别参数,降低误判概率:
    1. 执行xinput list查询鼠标对应的设备ID
    2. 执行xinput set-prop <你的鼠标设备ID> "libinput Click Method Enabled" 0, 1关闭宽松点击容错
    3. 若使用无线鼠标,可关闭蓝牙节能模式:修改/etc/bluetooth/main.conf,设置AutoEnable=false后执行sudo systemctl restart bluetooth重启蓝牙服务即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 20:24:05