每次在 Windows 中按下一个键时,我都使用此代码记录一次按键。在我看来,代码是完美的;没有不必要的循环或未定义的变量,它应该工作得很好。
但是,我一直在终端中得到这个:
Everything Imported Successfully
Starting Loop
Beginning Checks
Traceback (most recent call last):
File "C:\Users\***\relogged.pyw", line 15, in <module>
loop(OldKeyChar=[])
File "C:\Users\***\relogged.pyw", line 9, in loop
if OldKeyChar[num] == '1': #check to see if key was pressed
IndexError: list index out of range
我错过了什么?它应该可以工作,但是我的代码会导致错误。
import win32api
print("Everything Imported Successfully")
def loop(OldKeyChar):
print("Beginning Checks")
while(True): #always checking
for num in range(0,127): #iterate through list of ascii codes
if not win32api.GetAsyncKeyState(num): #if key is not being pressed
if OldKeyChar[num] == '1': #check to see if key was pressed
OldKeyChar[num] = '0' #make sure not recorded again
else:
OldKeyChar[num] = '1' #add pressed key to pressed list
OldKeyChar = ['0' for i in range(0,127)]
print("Starting Loop")
loop(OldKeyChar=[])