前言:之前和朋友玩游戏,需要一直按住两个按键,很麻烦。就像用python写个小脚本来方便自己,说干就干。(用于学习)
正文:
用到的库:
- keyborad
- threading
- tkinter
- time
分析:由于需要监听键盘与运行可视化界面,所以要用的python的多线程模块:threading。
线程:
- 监听键盘,是否运行/停止键盘宏。
- GUI界面线程。
- 键盘宏运行线程。
一,编写:
利用tkinter模块构造前端:
class GUI(threading.Thread): #从threading.Thread中继承一个新的子类 def __init__(self): threading.Thread.__init__(self) global text_list text_list = [] def run(self): global d,f,h23 windows = tk.Tk() windows.title = '键盘精灵' windows.geometry('500x500') a = tk.Label(windows, text='请按照你需要键盘顺序,按下键盘按键:\n例如:你需要让键盘循环输入:”Q“+"W"+"E"+"R"\n在下面右边的输入框输入:qwer\n开始热键为e,停止热键为t', bg='white', font=('Arial', 12), width=40, heigh=5) a.pack(side='top', expand='no', fill='x') c1 = tk.Button(windows, text='任意位置插入', bg='white', font=('Arial', 12), width=20, heigh=1, command=self.insert) c2 = tk.Button(windows, text='末尾位置插入', bg='white', font=('Arial', 12), width=20, heigh=1, command=self.end) c3 = tk.Button(windows, text='清空', bg='white', font=('Arial', 12), width=20, heigh=1, command=self.clear) c4 = tk.Button(windows, text='确定', bg='white', font=('Arial', 12), width=20, heigh=1, command=self.ok) f = tk.Text(width='40', heigh='1') f.pack(side='left', expand='yes', fill='both', anchor='w') d = tk.Entry(windows, show=None, width=50, font=('Arial', 30)) d.pack(side='top', expand='yes', fill='both', anchor='n') c1.pack(side='top', expand='yes', fill='both') c2.pack(side='top', expand='yes', fill='both') c3.pack(side='top', expand='yes', fill='both') c4.pack(side='top', expand='yes', fill='both') windows.mainloop() def insert(self): global d, f var = d.get() f.insert('insert', var) def end(self): global d, f var = d.get() f.insert('end', var) def clear(self): global d, f f.delete(0.0, 'end') def ok(self): global d, f h = f.get(0.0, 'end') text_list.extend(h)
然后就是编写后台的程序了:
#下面这个类是用于储存从前端获得的数据,并处理,方便下面程序利用 class judge(threading.Thread): def __init__(self): threading.Thread.__init__(self) global list list = [] pass def run(self): while True: global text_list a = text_list if len(a) > 0: if a != list: list.clear() list.extend(a) elif a==list: text_list.clear() elif len(a) == 0: time.sleep(1) pass #这个类是用于监听键盘的‘e’键,看是否开始运行键盘宏; class LISTEN(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): while True: keyboard.wait('e') LISTEN.QW(self) #下面这个函数,用于循环发送特定的按键,实现键盘宏; def QW(self): global n while True: for i in list: keyboard.send(i) time.sleep(0.1) # keyboard.send('w') # time.sleep(0.1) if n == 1: break if n == 1: n = 0 break #下面这个类是用来监听键盘,用户是否按下“t”键来退出键盘循环; class LISTEN_EXIT(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): global n while True: keyboard.wait('t') n = 1
最后就是将各个类,实例化运行:
if __name__ == '__main__': gui = GUI() JU = judge() listen = LISTEN() listen_exit = LISTEN_EXIT() gui.start() JU.start() listen.start() listen_exit.start() gui.join() JU.join() listen.join() listen_exit.join()
程序写的不是很好,有很多地方啰嗦或重复的地方,之后会不断完善。
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/215102.html原文链接:https://javaforall.net
