控制功能的键盘侦听器[python]

时间:2020-07-24 22:21:53

标签: python pynput

我想使用pynput为侦听器编码,该侦听器在键入某个键后可以打开和关闭功能。

就本例而言,假设我要打开和关闭的功能如下所示。因此,我希望我的程序成为一个非常简单的自动答题器,它可以使用用户指定的特定键来打开和关闭。

import pyautogui
from pynput.keyboard import Key, Listener
import time

def my_function():
    print("I'm on!")
    pyautogui.click()

我试图通过此脚本实现目标

break_program = True #a boolean variable which basically says 
#whether to start and finish the program

def make_string(key):
#a function just to make pynput work
    tmp_string = '"' + key + '"'
    return(tmp_string.replace('"', "'"))

def listener_function(user_key):
#that's my main function
    
    global break_program

    keys = [] #list to store use_keys only

    def on_press(key):    
        global break_program
    
        if str(key) == make_string(user_key):
        #the program checks whether the pressed key is the key given 
        #by the user (I know that it might be done better)
            keys.append(key)
        
        if key == Key.esc: #stop listening
            return(False)   

        if len(keys) > 0 and len(keys) % 2 == 1:
           break_program = False
        elif len(keys) > 0 and len(keys) % 2 == 0:
            break_program = True
        else:
            pass
        #the if block checks the parity of the amount user_key is 
        #pressed, if divisible by 2 the function is turned off

    with Listener(on_press=on_press) as listener: 
        print("break_program={}\n".format(break_program))
        while break_program == False:
            my_function()
            time.sleep(5)
        listener.start()
        listener.join()

侦听器正常工作,但是while循环无法正常工作。

我将不胜感激。

0 个答案:

没有答案