Reputation: 23
I'm just trying to make a program that will perform some keyboard inputs. I would like to put a delay between each key stroke, which I plan to make random in the future.
However, I am not sure how to use after()
with Tkinter. Without Tkinter, time.sleep
works fine - but with it, the GUI crashes.
Any help would be appreciated.
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()
Upvotes: 2
Views: 1106
Reputation: 3448
Firstly: the gui doesn't crash - it works fine and in the mainloop it executes the commands you are writing. It doesn't refresh, because it prints the output instead of refreshing UI. First notice you need to remember in creating a UI is that you should omit the unnecessary work in the main thread. Possible solution: Move the work to the separate thread and run it there, e.g.:
import time
import tkinter as tk
from pynput.keyboard import Controller as KeyboardController
import threading
keyboard = 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()
Upvotes: 1