Console选择python

问题描述 投票:0回答:4

如果我按箭头键,什么也不会发生。如果我按下一个,那么少于和大于符号将像这样上下移动:

Choose an option:
  1. Do something 1 
> 2. Do something 2 <
  3. Do something 3
  4. Do something 4

但是我不知道哪个Python 3模块可以帮助我捕捉钥匙按下,而不是

input()
,以及如何正确对齐。

我的对齐解决方案是打印空间(也许?),当按键事件是捕获量时,将清除控制台,然后再次打印选择菜单,而不是更改/修改字符串。

此外,选项还可以从列表中获取,这意味着此菜单可扩展

    

I为此写了一个Python模块

pick

,它易于使用API并支持Windows

python algorithm
4个回答
21
投票
https://github.com/wong2/pick

from pick import pick

title = 'Please choose your favorite programming language: '
options = ['Java', 'JavaScript', 'Python', 'PHP', 'C++', 'Erlang', 'Haskell']

option, index = pick(options, title, indicator='=>', default_index=2)

    

您必须检测键盘键。正如此enter image description heretectect键python中提到的答案时,python有一个键板

模块。

6
投票
pip install keyboard

Here's how it works Define a menu number range, in this case is 1 until 4

设置一个默认的选定菜单并用我们定义的数字表示,因此当用户打开菜单时,它将出现,在这种情况下为1

If a user press 
Up

key, you have decrement the selected menu number, except if it has been on the first element of the range. And vice versa for the

Down
    key, you have increment the selected menu number, except if it has been on the last element of the range.
  • import keyboard selected = 1 def show_menu(): global selected print("\n" * 30) print("Choose an option:") for i in range(1, 5): print("{1} {0}. Do something {0} {2}".format(i, ">" if selected == i else " ", "<" if selected == i else " ")) def up(): global selected if selected == 1: return selected -= 1 show_menu() def down(): global selected if selected == 4: return selected += 1 show_menu() show_menu() keyboard.add_hotkey('up', up) keyboard.add_hotkey('down', down) keyboard.wait()
上面的过程使代码变得更加混乱,并且需要在Linux上运行根特权。
最好的方法是使用

pip3 install enquiriesSample

使用以下代码

6
投票
import enquiries options = ['Do Something 1', 'Do Something 2', 'Do Something 3'] choice = enquiries.choose('Choose one of these options: ', options) print(choice)

我知道我迟到了这个问题,可能不是您想要的,但我想我还是为他人发布它。 您可以尝试使用Console-Menu,这是我在互联网上找到的模块,这很棒!

通过输入控制台

将其安装到使用PIP上
pip install console-menu

然后您可以在模块的情况下与它的文档一起玩耍。

Here's how it works
However, you cannot use the print() function while the window is open so I will use tkinter's messagebox to test with.

0
投票
# Import modules from consolemenu import * from consolemenu.items import * # For testing purposes from tkinter import messagebox # Needed for the menu menu = ConsoleMenu("Title", "Subtitle") # Defining the function def hello_world(): messagebox.showinfo(title = "Information", message = "Function was called") #Making the option to call the function function_item = FunctionItem("Hello World!", hello_world) # Now we need to add function_item menu.append(function_item) # Then make it visible menu.show()

console-menu's GitHub:

https://github.com/aegirhall/console-menu

    

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.