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

Python Kivy中如何实现按下Enter等按键时触发执行指定函数

Kivy 指定按键监听实现方法

Kivy 全局键盘事件绑定在Window核心对象上,不需要额外依赖,直接绑定on_key_down事件即可实现指定按键触发自定义函数的需求,核心步骤如下:

  • 导入kivy.core.window.Window全局窗口实例
  • 定义按键回调函数,按固定参数签名接收按键信息,通过按键名匹配目标按键
  • 绑定事件到Window实例,组件/页面销毁时记得解绑避免内存泄漏
  • 常用按键名参考:回车键为enter、ESC为escape、空格为spacebar、方向键对应up/down/left/right

最小可运行示例

from kivy.app import App
from kivy.core.window import Window
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label


class KeyListenLayout(BoxLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.orientation = "vertical"
        self.tip = Label(text="按下回车键触发预设函数,按ESC退出应用")
        self.add_widget(self.tip)
        # 绑定键盘按下事件,存下绑定id方便后续解绑
        self.key_bind_id = Window.bind(on_key_down=self.handle_key_press)

    def handle_key_press(self, window, keycode, scancode, codepoint, modifiers):
        # keycode是元组,格式为(按键数值编码, 按键字符串名)
        press_key = keycode[1]
        # 匹配回车键
        if press_key == "enter":
            self.enter_trigger_func()
        # 匹配ESC键
        elif press_key == "escape":
            App.get_running_app().stop()

    def enter_trigger_func(self):
        """回车键触发的自定义业务函数"""
        self.tip.text = "已检测到回车键按下,预设函数执行完成"
        print("回车键触发逻辑执行")

    def on_parent(self, *args):
        # 组件移除时解绑键盘事件
        if not self.parent:
            Window.unbind(on_key_down=self.key_bind_id)


class DemoApp(App):
    def build(self):
        return KeyListenLayout()


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

注意:如果页面中存在TextInput这类会主动消费键盘输入的组件,当组件获得输入焦点时,全局键盘事件可能被拦截,这种场景可以单独给输入组件绑定键盘事件,或者根据焦点状态做分支处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 23:33:19