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
如果你只想在按钮被点击时获取对应的触摸位置,还可以直接把触摸对象传给按钮回调:
- 先修改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)
- 再更新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
相关产品推荐
相关产品推荐

