gpt4 book ai didi

python - msvcrt getch 暂停脚本,必须继续

转载 作者:太空宇宙 更新时间:2023-11-03 18:42:56 29 4
gpt4 key购买 nike

PYTHON 3.3,msvcrt

import sys, msvcrt
print("Please press a key to see its value")
while 1:
key = msvcrt.getch()
print("the key is")
print(key)
if ord(key) == 27: # key nr 27 is escape
sys.exit()

这是我的代码,仅作为示例。当代码到达 key = msvcrt.getch()* 或 *key = ord(getch()) 时,代码会暂停,在这里我使用了第一个。我想让这段代码不断打印关键是当我给出新输入时(当我按下某个键时),而不是仅仅打印

所以打印输出看起来像这样:

the key is
the key is
the key is
the key is
the key is
the key is
77
the key is
the key is
the key is

如果您想要制作类似贪吃蛇之类的东西,您不希望每次想要获取时都暂停游戏,那么您不需要希望它暂停,等待输入。

最佳答案

使用msvcrt.kbhit检查是否按下了键:

import sys, msvcrt
import time

print("Please press a key to see its value")
while 1:
print("the key is")
if msvcrt.kbhit(): # <--------
key = msvcrt.getch()
print(key)
if ord(key) == 27:
sys.exit()
time.sleep(0.1)

关于python - msvcrt getch 暂停脚本,必须继续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20126833/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com