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

Kivy触摸输入问题:获取spos同时保留按钮回调函数

问题解决:同时获取触摸spos并保留按钮回调

这问题其实是Kivy事件传递机制的小坑——你重写on_touch_down时没调用父类的实现,导致触摸事件被拦截后没传递给子按钮,所以按钮的on_press回调就失效了。Kivy的触摸事件是从底层Widget向上传递的,如果你截住事件却不继续传递,子控件根本收不到触摸信号。

核心解决方案:调用父类的on_touch_down方法

在你的HomeScreen类的on_touch_down方法里,先执行super().on_touch_down(touch)让事件正常传递给子控件,之后再处理你自己的spos获取逻辑就行。

修改后的Python代码片段:

class HomeScreen(Screen):
    print('Start')
    port = "COM7"
    bluetooth = serial.Serial(port, 9600)
    print("Connected to HC-06")
    
    def button_press_down(self, *args):
        print("button pressed @location:")
        self.bluetooth.write(b"2")
    
    def button_press_up(self, *args):
        print("button pressed @location:")
        self.bluetooth.write(b"3")
    
    def on_touch_down(self, touch):
        # 先让父类处理触摸事件,确保按钮的on_press能触发
        handled = super().on_touch_down(touch)
        # 获取当前Screen范围内的触摸spos(归一化坐标)
        if self.collide_point(*touch.pos):
            print(f"Touch spos: {touch.spos}")
        return handled
    
    def on_touch_move(self, touch):
        pass

额外优化:精准获取按钮点击的spos

如果你只想在按钮被点击时获取对应的触摸位置,还可以直接把触摸对象传给按钮回调:

  1. 先修改kv文件里的按钮绑定:
Button:
    text: "Button_1"
    id:send_data_bluettooh
    on_press: root.button_press_down(touch)
Button:
    text: "Button_2"
    id:send_data_bluettooh_2
    on_press: root.button_press_up(touch)
  1. 再更新Python里的回调函数:
def button_press_down(self, touch):
    print(f"Button_1 pressed @spos: {touch.spos}")
    self.bluetooth.write(b"2")

def button_press_up(self, touch):
    print(f"Button_2 pressed @spos: {touch.spos}")
    self.bluetooth.write(b"3")

这种方式更精准,只会在按钮被点击时获取对应触摸的位置,不会捕获屏幕其他区域的触摸。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 14:48:12