如何制作一个不需要用户按[Enter]键进行选择的菜单?

StackOverflow https://stackoverflow.com/questions/1829

  •  08-06-2019
  •  | 
  •  

我有一个Python 菜单。那部分很容易。我在用着 raw_input() 获取用户的选择。

问题是 raw_input (和输入)要求用户按 进入 他们做出选择后。有没有办法让程序在按键时立即动作?这是我到目前为止所得到的:

import sys
print """Menu
1) Say Foo
2) Say Bar"""
answer = raw_input("Make a selection> ")

if "1" in answer: print "foo"
elif "2" in answer: print "bar"

拥有类似的东西就太好了

print menu
while lastKey = "":
    lastKey = check_for_recent_keystrokes()
if "1" in lastKey: #do stuff...
有帮助吗?

解决方案

在 Windows 上:

import msvcrt
answer=msvcrt.getch()

其他提示

在 Linux 上:

  • 设置原始模式
  • 选择并读取击键
  • 恢复正常设置
import sys
import select
import termios
import tty

def getkey():
    old_settings = termios.tcgetattr(sys.stdin)
    tty.setraw(sys.stdin.fileno())
    select.select([sys.stdin], [], [], 0)
    answer = sys.stdin.read(1)
    termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)
    return answer

print """Menu
1) Say Foo
2) Say Bar"""

answer=getkey()

if "1" in answer: print "foo"
elif "2" in answer: print "bar"

哇,那花了很长时间。好的,这就是我的结果

#!C:\python25\python.exe
import msvcrt
print """Menu
1) Say Foo 
2) Say Bar"""
while 1:
    char = msvcrt.getch()
    if char == chr(27): #escape
        break
    if char == "1":
        print "foo"
        break
    if char == "2":
        print "Bar"
        break

使用IDLE(Python 附带的东西)会失败。但是当我在 DOS 中(呃,CMD.exe)尝试它作为一个真正的程序时,它运行得很好。

没有人在空闲状态下尝试它,除非你手边有任务管理器。

我已经忘记了我是如何忍受那些不是超即时响应的菜单的。

msvcrt 在 IDLE 中失败的原因是 IDLE 未访问运行 msvcrt 的库。然而,当您在 cmd.exe 中本地运行该程序时,它运行得很好。与您的程序在 Mac 和 Linux 终端上崩溃的原因相同。

但我想如果你打算专门在 Windows 上使用它,那么你会拥有更多的能力。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top