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

如何在Windows终端创建支持键盘控制的菜单?simple_term_menu失效求助

解决Windows终端下simple_term_menu失效的方案

原因分析

simple_term_menu依赖Unix系统的termios模块处理终端输入,Windows原生无此模块,导致方向键选择、回车确认等核心交互逻辑无法正常工作。

替代方案1:使用prompt-toolkit(推荐)

prompt-toolkit是跨平台终端交互库,完美适配Windows各类终端(CMD、PowerShell、Windows Terminal),自带成熟的菜单交互逻辑。

首先安装库:

pip install prompt-toolkit

实现菜单的示例代码:

from prompt_toolkit.shortcuts import radiolist_dialog

def select_menu(options):
    # 生成带索引的选项列表,弹窗式菜单
    result = radiolist_dialog(
        title="菜单选择",
        text="使用方向键切换选项,回车确认:",
        values=[(idx, opt) for idx, opt in enumerate(options)]
    ).run()
    return result

# 测试代码
if __name__ == "__main__":
    menu_options = ["查看日志", "修改配置", "退出程序"]
    selected_idx = select_menu(menu_options)
    if selected_idx is not None:
        print(f"你选中了:{menu_options[selected_idx]}")

替代方案2:手动基于msvcrt实现轻量菜单

若不想引入第三方库,可利用Windows自带的msvcrt模块直接处理键盘输入,自行实现菜单逻辑:

import msvcrt
import os

def get_input_key():
    # 捕获方向键、回车键输入
    key = msvcrt.getch()
    if key == b'\r':
        return 'enter'
    # 方向键前缀字节,需读取第二个字节判断方向
    elif key in (b'\x00', b'\xe0'):
        second_key = msvcrt.getch()
        if second_key == b'H':
            return 'up'
        elif second_key == b'P':
            return 'down'
    return None

def render_menu(options):
    current_select = 0
    while True:
        # 清屏(兼容多数Windows终端)
        os.system('cls')
        print("菜单选择(方向键上下切换,回车确认):")
        for idx, opt in enumerate(options):
            # 高亮当前选中项
            if idx == current_select:
                print(f"-> *{opt}*")
            else:
                print(f"   {opt}")
        # 处理键盘输入
        key = get_input_key()
        if key == 'up':
            current_select = max(0, current_select - 1)
        elif key == 'down':
            current_select = min(len(options)-1, current_select + 1)
        elif key == 'enter':
            return current_select

# 测试代码
if __name__ == "__main__":
    options = ["选项1", "选项2", "选项3", "退出"]
    selected_idx = render_menu(options)
    print(f"选中结果:{options[selected_idx]}")

替代方案3:修复simple_term_menu(不推荐)

若坚持使用simple_term_menu,需手动适配Windows环境:

  1. 安装Windows依赖:pip install pywin32
  2. 找到simple_term_menu的源码文件,将termios相关的终端控制逻辑替换为win32console接口实现
    此方案需要对库内部逻辑有一定了解,稳定性较差,仅适合有定制需求的开发者。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 16:28:21