How would I implement if a key is held down?

邮差的信 提交于 2019-12-13 03:49:46

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!