文章目录
1. 按2. 安装3. 按键字符4. 常用方法4.1. [wait()](/boppreh/keyboard#keyboard.wait)4.2. [add_hotkey()](/boppreh/keyboard#keyboard.add_hotkey)4.3. [record()](/boppreh/keyboard#keyboard.record)4.4. [hook()](/boppreh/keyboard#keyboard.hook)4.5. [on_press()](/boppreh/keyboard#keyboard.on_press)4.6. [KeyboardEvent()](/boppreh/keyboard#keyboard.KeyboardEvent)4.7. [全部API](/boppreh/keyboard#api)1. 按
监听鼠标事件可以参考:Python借助pynput监听鼠标事件
2. 安装
PyPI主页
Github
pip install keyboard
如果使用国外的源下载速度慢,我们可以使用国内的源进行提速:
豆瓣源
pip3 install keyboard -i /simple
清华大学源
pip3 install keyboard -i https://pypi.tuna./simple
3. 按键字符
#字符'1''a'...#控制'ctrl''alt''shift''enter''esc''f1'...#方向键'up''down''left''right'#组合按键'ctrl'+'alt'+'a'...
4. 常用方法
4.1. wait()
监听按键,如果没设置按键,将会一直监听这句之前的按键;如果设置了按键,那么在按下该按键后就会停止监听,并执行后面的语句,举例:
import keyboardprint(0)keyboard.wait('a')#在按下a之前后面的语句都不会执行,下面同理print(1)keyboard.wait('b')print(2)keyboard.wait('c')print(3)keyboard.wait()# 结果:# 0# 1# 2# 3#继续监听#只有按顺序按下abc(中间过程随便按不干扰)才能输出0123,但因为最后一个没设置按键,所以会一直监听下去
4.2. add_hotkey()
设置热键,一般和wait()组合使用,在wait监听下,当按下热键时会执行对应函数,举例:
import keyboard #监听键盘def test_a():print('aaa')def test(x):print(x)if __name__ == '__main__':keyboard.add_hotkey('f1', test_a)#按f1输出aaakeyboard.add_hotkey('ctrl+alt', test, args=('b',))#按ctrl+alt输出bkeyboard.wait()#wait里也可以设置按键,说明当按到该键时结束
4.3. record()
记录键盘事件,如果加上until参数,可以设置当按下某按键时结束监听,和wait方法有点像,举例:
import keyboardkeyboard.add_hotkey('ctrl', print, args=('aaa',))keyboard.add_hotkey('alt', print, args=('bbb',))recorded = keyboard.record(until='esc')#当按下esc时结束按键监听,并输出所有按键事件print(recorded)# 结果为:# aaa# aaa# bbb# [KeyboardEvent(ctrl down), KeyboardEvent(ctrl up), KeyboardEvent(ctrl down), # KeyboardEvent(ctrl up), KeyboardEvent(alt down), KeyboardEvent(alt up),# KeyboardEvent(esc down)]
4.4. hook()
绑定所有按键事件,当只要有按键按下/松开时就会触发的回调函数,举例:
import keyboarddef callback(x):print(x)print()keyboard.hook(callback)# 按下任何按键时,都会调用callback,其中一定会传一个值,就是键盘事件keyboard.wait()
4.5. on_press()
按下及长按任何按键时均会触发回调函数
import keyboarddef callback(x):print(x)print()keyboard.on_press(callback)# 按下任何按键时(包括长按),都会调用callback,其中一定会传一个值,就是键盘事件keyboard.wait()
4.6. KeyboardEvent()
一个按键事件,里面有3个常用参数:event_type、scan_code、name,分别代表按键类型(down/up)、按键号(每个键都有对应的)和按键名,举例:
import keyboarddef abc(x):a = keyboard.KeyboardEvent('down', 28, 'enter')#按键事件a为按下enter键,第二个参数如果不知道每个按键的值就随便写,#如果想知道按键的值可以用hook绑定所有事件后,输出x.scan_code即可if x.event_type == 'down' and x.name == a.name:print("你按下了enter键")#当监听的事件为enter键,且是按下的时候keyboard.hook(abc)# keyboard.hook_key('enter', bcd)# recorded = keyboard.record(until='esc')keyboard.wait()# 结果:# 你按下了enter键# 你按下了enter键