[英]Python Windows `msvcrt.getch()` only detects every 3rd keypress?
我的代碼如下:
import msvcrt
while True:
if msvcrt.getch() == 'q':
print "Q was pressed"
elif msvcrt.getch() == 'x':
sys.exit()
else:
print "Key Pressed:" + str(msvcrt.getch()
這段代碼就是基於這個問題 ; 我正在用它來熟悉getch
。
我注意到,需要3次按3次鍵才能輸出一次文本。 為什么是這樣? 我正在嘗試將其用作事件循環,這太滯后了...
即使我鍵入3個不同的鍵,它也只會輸出第3個按鍵。
我如何強迫它更快? 有沒有更好的方法來實現我要達到的目標?
謝謝!
逃避
您可以在循環中調用該函數3次。 嘗試只這樣調用一次:
import msvcrt
while True:
pressedKey = msvcrt.getch()
if pressedKey == 'q':
print "Q was pressed"
elif pressedKey == 'x':
sys.exit()
else:
print "Key Pressed:" + str(pressedKey)
您還可以通過使用msvcrt.kbhit
函數進行一些優化,該函數將允許您僅在必要時調用msvcrt.getch()
:
while True:
if msvcrt.kbhit():
ch = msvcrt.getch()
if ch in '\x00\xe0': # arrow or function key prefix?
ch = msvcrt.getch() # second call returns the scan code
if ch == 'q':
print "Q was pressed"
elif ch == 'x':
sys.exit()
else:
print "Key Pressed:", ch
請注意,打印的Key Pressed
值對於功能鍵之類的東西沒有意義。 這是因為在這種情況下,它實際上是鍵的Windows 掃描代碼 ,而不是字符的常規鍵代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.