按键按下时记录按键值,按键抬起时删除按键值,同时检查是否同时存在两个设定键值,直接上代码:
from pynput.keyboard import Key,Controller,Listenerrecord_key = []def on_press(key):try:record_key.append("{}".format(key.char))except:record_key.append("{}".format(key))def on_release(key): try:# print(record_key)if 'Key.cmd' in record_key:if 'z' in record_key:Web_search()if 'Key.alt_l' in record_key:DB_search()try:record_key.remove("{}".format(key.char))except:record_key.remove("{}".format(key))except:print('键盘监控失败,有按键处于按下状态!')return Falseif key == Key.esc: return Falsedef Web_search():print('enter Web_search!')def DB_search():print('enter DB_search!')if __name__ == '__main__':with Listener( on_press = on_press,on_release = on_release) as listener:listener.join()
还有可以更简单:
from pynput.keyboard import Key,Controller,Listenerrecord_key = []def on_press(key):record_key.append(str(key))def on_release(key): print(record_key)if 'Key.cmd' in record_key:if "'z'" in record_key:Web_search()if 'Key.alt_l' in record_key:DB_search()if len(record_key)>0:record_key.remove(str(key))if key == Key.esc: return Falsedef Web_search():print('enter Web_search!')def DB_search():print('enter DB_search!')if __name__ == '__main__':with Listener( on_press = on_press,on_release = on_release) as listener:listener.join()