使用pynput
模塊:(最佳)
您可以使用此代碼:
from pynput import keyboard
import time
def callb(key): #what to do on key-release
ti1 = time.time() - t
ti1 = str(ti1) #converting float value to string
ti2 = ti1[0:5] #cutting the seconds (time) , without it , it will print like 0.233446546
print("The key",key,"Pressed For",ti2,'seconds')
return False #stop detecting more key-releases
def callb1(key): #what to do on key-press
return False #stop detecting more key-presses
with keyboard.Listener(on_press = callb1) as listener1: #setting code for listening key-press
listener1.join()
t = time.time()
with keyboard.Listener(on_release = callb) as listener: #setting code for listening key-release
listener.join()
注:
我不知道如果pynput
是內置的模塊,如果你收到ModuleNotFoundError
然後用pip
進行安裝:
pip install pynput
使用pygame
:(良好)
import time
import pygame
import os
os.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)
注:
它只能檢測到您將在代碼編寫的關鍵。
PyGame有'KEYDOWN'和'KEYUP'事件,所以你可以得到時間和減少。 – furas
所有'GUI'都應該有方法來獲得'KEYDOWN'和'KEYUP'事件。 – furas
我的回答有什麼不正確的地方嗎? :) –