赞
踩
最近玩上了某款游戏,由于游戏中打怪需要一直按键盘上固定的几个键,时间一长手就会很累,为了解放左手,楼主自行实现了一款按键精灵。
言归正传,本款按键精灵是用python语言实现的,下面介绍一下实现方法:
1.pykeyboard库用来模拟按压键盘的操作
2.pynput库用来监听键盘按压事件
3.threading库用来抛出线程,实现循环按压
4.tkinter库用来实现一个简单的UI界面
介绍一下按键精灵的功能:
1.代码运行后,自动实现键盘按键“1,2,3,4,5,6”的循环按压
2.按“-”键时,暂停循环按压
3.按“+”键时,继续循环按压
4.点击UI界面退出按钮,退出按键精灵
exe文件暂时没有上传,感兴趣的可以自行打包。
代码如下:
from pykeyboard import PyKeyboard import time, threading import tkinter as tk from pynput import keyboard, mouse def on_press(key): try: # print('key {0} pressed'.format(key.char)) if key.char is '-': print('"-" press, pause...') a.pause() if key.char is '=': print('"+", continue...') a.resume() except AttributeError: print('key {0} pressed'.format(key)) def on_release(bool_value): if bool_value is not True: return bool_value class Job(threading.Thread): def __init__(self, *args, **kwargs): super(Job, self).__init__(*args, **kwargs) self.__flag = threading.Event() self.__flag.set() self.__running = threading.Event() self.__running.set() self.k = PyKeyboard() def key_tap(self, key_value, dur_time): self.k.tap_key(key_value) print('press ' + key_value) time.sleep(dur_time) def run(self): while self.__running.isSet(): self.__flag.wait() # 为True时立即返回, 为False时阻塞直到内部的标识位为True后返回 self.key_tap('1', 0.5) self.key_tap('2', 0.5) self.key_tap('3', 0.5) self.key_tap('4', 0.5) self.key_tap('5', 0.5) self.key_tap('6', 0.5) def pause(self): self.__flag.clear() b2['bg'] = 'Chartreuse' b1['bg'] = 'WhiteSmoke' def resume(self): self.__flag.set() b1['bg'] = 'Chartreuse' b2['bg'] = 'WhiteSmoke' def stop(self): self.__flag.set() self.__running.clear() def exit(): a.stop() on_release(False) win.quit() win = tk.Tk() a = Job() a.start() keyboard_listener=keyboard.Listener(on_press=on_press,on_release=on_release) keyboard_listener.start() win.title('按键精灵') win.resizable(width=False, height=False) win.update() scnWidth,scnHeight = win.maxsize() tmpcnf = '%dx%d+%d+%d'%(628, 120, (scnWidth-350)/2, (scnHeight-200)/2) win.geometry(tmpcnf) b1=tk.Button(win, text='继续', font=('宋体 30 bold'), bg='WhiteSmoke', width=9, height=2, command=a.resume) b1.grid(row=0, column=0, sticky=tk.W, padx=5, pady=5) b2=tk.Button(win, text='暂停', font=('宋体 30 bold'), bg='WhiteSmoke',width=9, height=2, command=a.pause) b2.grid(row=0, column=1, sticky=tk.W, padx=5, pady=5) b3=tk.Button(win, text='退出', font=('宋体 30 bold'), bg='WhiteSmoke',width=9, height=2, command=exit) b3.grid(row=0, column=2, sticky=tk.W, padx=5, pady=5) win.mainloop()
功能演示:
程序的创造源于生活中的需求
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。