问题
I've searched a lot of threads about this issue but none seem to meet my needs. I'm intending on implementing this code into a script that uses the terminal for use, so using something like pygame is really awkward. I'm doing this for personal use, so any Windows OS dependent solutions would work.
Essentially, I want Python to make the variable keyState equal to LOW if a key is pressed/held and HIGH as long as it's not being pressed. I've tried using mscvrt but it hasn't worked. I would think this would world, but it doesn't :
import msvcrt
keyState = 'HIGH'
while True:
while msvcrt.kbhit():
isPressed = 'LOW'
print(isPressed)
msvcrt.getch()
isPressed = 'HIGH'
print(isPressed)
I understand this is pretty simple, but I've had a lot of trouble getting something really simple like this to work. Any help is appreciated :)
Another solution that can somehow make keyPressed a boolean variable that's true whenever a key is pressed/held seems like the most elegant solution, but I'm fine with using anything!
Thanks!
回答1:
Try this (untested)
import msvcrt
import time
keystate = 'HIGH'
while True:
if msvcrt.kbhit():
keystate = 'LOW'
msvcrt.getch()
else:
keystate = 'HIGH'
# you may want to put a time.sleep() call here
# to avoid eating up CPU
time.sleep(0.1)
print(keystate)
回答2:
If anyone comes here for reference, here is my final code that will output HIGH or LOW once the state changes. Make sure your keyboard delay speed on Windows is set to the fastest it can be
import msvcrt
import time
keyState = 'HIGH'
while True:
if msvcrt.kbhit():
if keyState != 'LOW':
keyState = 'LOW'
time.sleep(0.2)
print(keyState)
msvcrt.getch()
else:
if keyState != 'HIGH':
keyState = 'HIGH'
print(keyState)
time.sleep(0.1)
来源:https://stackoverflow.com/questions/45155643/how-would-i-implement-if-a-key-is-held-down