发出一个代码来注册第一个100键的按下和长度

2024-05-13 11:49:18 发布

您现在位置:Python中文网/ 问答频道 /正文

需要你的帮助,它只适用于第一个。。。 这个想法是注册前100个按键的时间和长度,他们被按下

from pynput import keyboard 
import time, os

tinit = time.time()
Resultatfichier=open('Keyregister','a')
x = 1

def callb(key): #what to do on key-release
    ti1 = str(time.time() - t)[0:8] #converting float to str, slicing the float
    ti2 = str(time.time() - tinit)[0:8] #converting float to str, slicing the float
    Resultatfichier.write("At "+ti2+" The key " + str(key) + " is pressed for "+ ti1 + " seconds\n") 
    x = x + 1
    return False #stop detecting more key-releases
def callb1(key): #what to do on key-press
    return False #stop detecting more key-presses

while x <= 100:  
    with keyboard.Listener(on_press = callb1) as listener1: #setting code for listening key-press
        listener1.join()

        t = time.time() #reading time in sec

    with keyboard.Listener(on_release = callb) as listener: #setting code for listening key-release
        listener.join()

Resultatfichier.close()

Tags: tokeyimportforreleasetimeondef
1条回答
网友
1楼 · 发布于 2024-05-13 11:49:18

我测试了您的代码,如果您在callb函数中声明global x,似乎可以正常工作:

from pynput import keyboard 
import time, os

tinit = time.time()
Resultatfichier=open('Keyregister','a')
x = 1

def callb(key): #what to do on key-release
    global x # if not then 'x' is assigned before creation because of scope of variable
    ti1 = str(time.time() - t)[0:8] #converting float to str, slicing the float
    ti2 = str(time.time() - tinit)[0:8] #converting float to str, slicing the float
    Resultatfichier.write("At "+ti2+" The key " + str(key) + " is pressed for "+ ti1 + " seconds\n") 
    x = x + 1
    return False #stop detecting more key-releases
def callb1(key): #what to do on key-press
    return False #stop detecting more key-presses

while x <= 10:  
    with keyboard.Listener(on_press = callb1) as listener1: #setting code for listening key-press
        listener1.join()

        t = time.time() #reading time in sec

    with keyboard.Listener(on_release = callb) as listener: #setting code for listening key-release
        listener.join()

Resultatfichier.close()

相关问题 更多 >