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

使用keyboard包开发控制台菜单时类内变量self.current更新不生效

问题原因
  • 热键重复注册:你在run方法的while循环内部重复绑定up和down的热键,每一轮循环都会新增一次回调,按一次方向键会触发多次self.up/self.down方法,导致self.current的实际值和你预期的偏移量不符
  • 阻塞调用导致状态不一致:错误分支中的input()是同步阻塞调用,期间的按键事件不会被keyboard库的热键逻辑捕获,容易出现状态错位
  • 不必要的热键解绑/注册开销:每次按下回车后你都解绑所有热键,下一轮循环又重新绑定,本身也会增加异常概率
解决方案

修改run方法的逻辑,把热键注册移到循环外部,同时调整错误提示的交互逻辑:

def run(self):
    # 热键只注册一次即可
    keyboard.add_hotkey('up', self.up)
    keyboard.add_hotkey('down', self.down)
    try:
        while True:
            self.show_menu(self.error)
            # 等待回车按下
            keyboard.wait("enter")
            if self.current == len(self.choices) and len(self.choiceSelected) != 0:
                return self.choiceSelected
            elif self.current == len(self.choices):
                self.error = "\n" + bcolors.WARNING + "ERROR: Nothing selected!" + bcolors.ENDC
                # 清理未消费的按键事件,避免误触
                keyboard.read_event(suppress=True)
            else:
                # 原逻辑缺失按回车切换选项选中状态的代码,此处补充
                if self.current in self.choiceSelected:
                    self.choiceSelected.remove(self.current)
                else:
                    if len(self.choiceSelected) < self.maxChoices:
                        self.choiceSelected.append(self.current)
                self.error = ""
    finally:
        # 退出前统一解绑所有热键
        keyboard.unhook_all_hotkeys()
补充说明

请确认你的self.up和self.down方法里已经做了边界校验,self.current的取值范围必须控制在0 ~ len(self.choices)之间,不能低于0也不能超过选项总长度(含末尾的confirm项)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 18:54:04