Pynput 按键延迟和 Tkinter

我只是想制作一个程序来执行一些键盘输入。我想在每次击键之间设置一个延迟,我计划在将来随机设置。


但是,我不确定如何after()与 Tkinter 一起使用。没有 Tkinter,time.sleep工作正常 - 但有了它,GUI 崩溃了。


任何帮助,将不胜感激。


import time

import tkinter as tk

from pynput.keyboard import Key, Controller as KeyboardController

from pynput.mouse import Button, Controller as MouseController


keyboard = KeyboardController()

mouse = MouseController()




def copy(a):

    pause_input=17

    pause_input2=2

    pause_input3=0.5

    x=1

    while a >= x:

        x = x+1

        time.sleep(pause_input)

        keyboard.press('t')

        keyboard.release('t')

        time.sleep(pause_input3)

        keyboard.press('e')

        keyboard.release('e')

        time.sleep(pause_input3)

        keyboard.press('s')

        keyboard.release('s')

        keyboard.press('t')

        keyboard.release('t')

        

root = tk.Tk()

root.title("GUI Button")

btn1 = tk.Button(root, text="Button 1", command=lambda : copy(360))

btn2 = tk.Button(root, text="Button 2")


btn1.pack()

btn2.pack()



root.mainloop()


月关宝盒
浏览 122回答 1
1回答

MYYA

首先:gui 不会崩溃 - 它工作正常并且在主循环中它执行您正在编写的命令。它不会刷新,因为它打印输出而不是刷新 UI。首先请注意,在创建 UI 时需要记住的是,您应该省略主线程中不必要的工作。可能的解决方案:将工作移至单独的线程并在那里运行,例如:import timeimport tkinter as tkfrom pynput.keyboard import Controller as KeyboardControllerimport threadingkeyboard = KeyboardController()def copy(a):    def print_test(a):        pause_input=2        pause_input2=2        pause_input3=0.5        for _ in range(a):            time.sleep(pause_input)            keyboard.press('t')            keyboard.release('t')            time.sleep(pause_input3)            keyboard.press('e')            keyboard.release('e')            time.sleep(pause_input3)            keyboard.press('s')            keyboard.release('s')            keyboard.press('t')            keyboard.release('t')            print("Wrote test")    t = threading.Thread(target=print_test, args=(a,))    t.start()        root = tk.Tk()root.title("GUI Button")btn1 = tk.Button(root, text="Button 1", command=lambda : copy(360))btn1.pack()root.mainloop()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python