如何将Python inquirer复选框的选中/未选中符号从X和o改为Y和N
修改inquirer复选框选中/未选中标识方法
问题场景
使用Python的inquirer库构建交互式命令行复选框时,默认选中项前缀为X、未选中项前缀为o,默认效果如下:
[?] What are you interested in?: X Computers o Books
由于X/o的组合容易让人联想到代表“拥抱和亲吻”含义的XOXO,在部分正式工作场景使用不够妥当,需要将两个标识分别替换为表意更清晰的Y(选中)和N(未选中)。
原始示例脚本:
import os import sys from pprint import pprint import yaml sys.path.append(os.path.realpath(".")) import inquirer # noqa questions = [ inquirer.Checkbox( "interests", message="What are you interested in?", choices=["Computers", "Books", "Science", "Nature", "Fantasy", "History"], default=["Computers", "Books"], ), ] answers = inquirer.prompt(questions) pprint(answers) print(yaml.dump(answers))
实现方法
inquirer支持通过自定义主题修改控件渲染样式,不需要修改库源码,只需要继承默认主题类,覆写复选框对应的图标配置,再将自定义主题传入prompt方法即可。
修改后的完整代码:
import os import sys from pprint import pprint import yaml from inquirer.themes import Default as DefaultTheme sys.path.append(os.path.realpath(".")) import inquirer # noqa # 自定义适配工作场景的主题 class WorkSceneTheme(DefaultTheme): def __init__(self): super().__init__() # 选中状态标识改为Y self.Checkbox.selected_icon = "Y" # 未选中状态标识改为N self.Checkbox.unselected_icon = "N" questions = [ inquirer.Checkbox( "interests", message="What are you interested in?", choices=["Computers", "Books", "Science", "Nature", "Fantasy", "History"], default=["Computers", "Books"], ), ] # 传入自定义主题执行交互 answers = inquirer.prompt(questions, theme=WorkSceneTheme()) pprint(answers) print(yaml.dump(answers))
运行后输出效果如下,标识已经替换完成:
[?] What are you interested in?: Y Computers N Books
注:除了复选框图标外,主题类还支持修改光标样式、颜色、选中高亮等所有命令行交互的渲染样式,可以根据实际场景需求调整。
内容的提问来源于stack exchange,提问作者puravidaso
相关产品推荐
相关产品推荐

