自己一边百度一边弄了一些代码, 想要实现: 1:有一个按钮能启动程序 2:实现键盘监听,当按下d键时,暂停进程2 3:正常需要运行的程序 但是自己写的程序就是无法运行,代码如下
from pynput.keyboard import Listener import os from multiprocessing import Process import psutil from tkinter import * import pyautogui import time import threading def clicked(): def work1(pid, mainpid): # 按键监听,当按下“d"键时弹窗 def on_press(key): all_key = [] all_key.append(str(key)) if "'d'" in all_key: pause = psutil.Process(pid) # 传入子进程的pid pause.suspend() # 暂停子进程 print(f'{pid}子进程已暂停。。。。') def on_release(key): all_key = [] all_key.append(str(key)) if "'d'" in all_key: def zzcx(): pipause = psutil.Process(mainpid) # 传入主进程的pid pipause.kill() print(f'{mainpid}主进程已结束。。。。') tanchuan_zt.destroy() def jxcx(): pause = psutil.Process(pid) # 传入子进程的pid pause.resume() # 暂停子进程 print(f'{pid}子进程已继续。。。。') # 设置弹窗 tanchuan_zt = Tk() tanchuan_zt.title("终止/暂停程序") wb_zt = Label(tanchuan_zt, text="您按下了”D(d)“键,此为暂停程序键,\n请问是否继续", compound=CENTER, font=("楷体", 20), fg="black") wb_zt.pack(pady=20) xx1_button = Button(tanchuan_zt, text="终止程序", command=zzcx) xx1_button.pack(side="left", padx=120) xx2_button = Button(tanchuan_zt, text="继续程序", command=jxcx) xx2_button.pack(side="right", padx=120) # 弹窗位置大小设置 width = 700 height = 200 screenwidth = tanchuan_zt.winfo_screenwidth() screenheight = tanchuan_zt.winfo_screenheight() alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2) tanchuan_zt.geometry(alignstr) tanchuan_zt.mainloop() all_key.clear() # 对列表进行清空 # if key == Key.esc: # 停止监听 # return Falseurn False def start_listen(): # 设置监听 with Listener(on_press=on_press, on_release=on_release) as listener: listener.join() start_listen() # 启动监听 def run(): a = 0 while a != 10: op = pyautogui.locateCenterOnScreen('C:\\Users\\59452\\Desktop\\op.png', confidence=0.9) print(op) pyautogui.click(op) pyautogui.moveTo(100, 100) time.sleep(2) a += 1 print(a) if __name__ == '__main__': mainpid = os.getpid() # 获取主进程pid p2 = Process(target=run) p2.start() pid = p2.pid # 获取子进程pid p1 = Process(target=work1, args=(pid, mainpid)) p1.start() window = Tk() window.title("Auto Script") window.geometry("400x400") btn1 = Button(window, text="Click Me", command=lambda : threading.Thread(target=clicked).start()) btn1.pack() window.mainloop()