期望用户输入()时如何检测“ESC"按键 [英] How to Detect 'ESC' keypress while expecting input() from user
本文介绍了期望用户输入()时如何检测“ESC"按键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试使用
if msvcrt.kbhit():
key_stroke = msvcrt.getch()
if key_stroke==chr(27).encode(): #b'\x1b'
print ("Esc key pressed")
sys.exit()`
在 data=input('Enter a value:')
之前和之后,但是 Esc key_stroke 没有被检测到
before and after the data=input('Enter a value:')
but the Esc key_stroke not getting detected
也就是说,在期望用户使用 input() 函数输入时,如果用户按下 Esc 键,我想做 sys.exit()
That is, while expecting an input from user with input() function, if the user press Esc key, I want to do sys.exit()
推荐答案
试试这个:
import sys
import msvcrt
def func():
print ('Enter user input:')
while True:
if msvcrt.kbhit():
key_stroke = msvcrt.getche()
if key_stroke==chr(27).encode():
print ("Esc key pressed")
sys.exit()
else:
#print (str(key_stroke).split("'")[1],"key pressed")
i=str(key_stroke).split("'")[1]+input()
print ("User input:",i)
func()
注意:我使用的是 getche 而不是 getch,它与 getch 类似,但会打印按下的键.
Note: I am using getche instead of getch, it is similar to getch but prints the key that is pressed.
这篇关于期望用户输入()时如何检测“ESC"按键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文