似乎无法得到.getch()工作(Python 2.7)
问题描述:
我试图检测一个按键来确定用户是否想再次播放,但msvcrt.getch()只是不适合我。这是我的代码:似乎无法得到.getch()工作(Python 2.7)
import msvcrt
#the game here
print "Do you want to continue? Y/N"
if msvcrt.getch() == 'Y' or msvcrt.getch() == 'y':
print"Let's play again!"
print"-----------------"
elif msvcrt.getch() == 'N' or msvcrt.getch() == 'n' :
"Okay, hope you had fun"
break
有什么建议吗?
编辑:下面这些问题的答案就在命令行中运行,由于某种原因,只是不要在PyCharm
答
你应该只调用msvcrt.getch()
一次。将您的代码更改为如下所示:
import msvcrt
#the game here
print "Do you want to continue? Y/N"
response = msvcrt.getch()
if response.lower() == 'y':
print"Let's play again!"
print"-----------------"
elif response.lower == 'n' :
"Okay, hope you had fun"
break
+0
是的,这是有道理的,但它仍然无法正常工作。只是似乎没有注册按键出于某种原因。 – sOfekS
运行代码时是否有任何错误? – cosinepenguin
您需要调用'getch()'__once__,然后比较该值四次。事实上,你只是比较用户的初始按键和Y按键,然后请求第二个按键。 – jasonharper
@cosinepenguin @jasonharper没有错误,只是没有注册任何按键,就好像'getch()'doesn出于某种原因甚至不会被召唤。 – sOfekS