#使用
pynput模块:( 最佳)
您可以使用以下代码:
from pynput import keyboard import timedef on_key_release(key): #what to do on key-release time_taken = round(time.time() - t, 2) #rounding the long decimal float print("The key",key," is pressed for",time_taken,'seconds') return False #stop detecting more key-releasesdef on_key_press(key): #what to do on key-press return False #stop detecting more key-presseswith keyboard.Listener(on_press = on_key_press) as press_listener: #setting pre for listening key-press press_listener.join()t = time.time() #reading time in secwith keyboard.Listener(on_release = on_key_release) as release_listener: #setting pre for listening key-release release_listener.join()
#使用
pygame:( 好)
import timeimport pygameimport osos.environ["SDL_VIDEO_CENTERED"] = "1"screen = pygame.display.set_mode((600, 600))pygame.display.set_caption("Time")clock = pygame.time.Clock()pygame.init()clock = pygame.time.Clock()running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False pygame.quit() break if event.type == pygame.KEYDOWN: # detect key 'a' if event.key == pygame.K_a: # key 'a' t = time.time() if event.type == pygame.KEYUP: if event.key == pygame.K_a: # key 'a' t = time.time() - t; t = str(t); t = t[:5] print("You pressed key 'a' for",t,'seconds') screen.fill((255, 255, 255)) pygame.display.update() clock.tick(40)
它只会检测您将在代码中编写的键。
使用
pip install pynput安装
pynput。
使用
pip install pygame安装
pygame。