First, my code:
when = tk.Tk()
when.title("when (sec)")
when.geometry('250x120')
def WhenInput():
print(when.get(1.0, "end"))
when = tk.Text(when, height = 10, width = 10)
when.pack()
when.mainloop()
StartIn = WhenInput
ClickDelay = 0.05
ClickRepeat = 20
mouse = Controller()
time.sleep(StartIn)
def repeat():
mouse.press(Button.left)
time.sleep(ClickDelay)
mouse.release(Button.left)
for i in range(ClickRepeat):
repeat()
What I want it to do is to open a text box, I insert a number for example 5, I close the window and the 5 gets put into the "StartIn" variable.
What I want my code to do when it’s ready: It opens 3 text boxes, one after another where I first input the when, then the how fast and then how much. It’s an autoclicker.
If you want you can suggest better solutions.
CodePudding user response:
import tkinter as tk
import time
from pynput.mouse import Controller, Button
StartIn = 0
when = tk.Tk()
when.title("when (sec)")
when.geometry('250x120')
def WhenInput():
return int(when_text.get(1.0, "end-1c"))
when_text = tk.Text(when, height = 10, width = 10)
when_text.pack()
def on_closing():
global StartIn
StartIn = WhenInput()
when.destroy()
when.protocol("WM_DELETE_WINDOW", on_closing)
when.mainloop()
ClickDelay = 0.05
ClickRepeat = 20
mouse = Controller()
time.sleep(StartIn)
def repeat():
mouse.press(Button.left)
time.sleep(ClickDelay)
mouse.release(Button.left)
for i in range(ClickRepeat):
repeat()
Explanation
First Thing What Is Wrong In Your Code.
- Your main root name which is
when = tk.Tk()and the text input name is the same which iswhen. - You try to get the input text value after the root is destroyed.
Which is gives you this error
_tkinter.TclError: invalid command name ".!text".
What I Have Changed.
- First I change the same variable name.
- Add an event which is
protocol("WM_DELETE_WINDOW", on_closing)which is executed when someone tries to exit or destroy the window. You notice that I passon_closingas a parameter. This is because when someone tries to exit or destroy the window theprotocol("WM_DELETE_WINDOW", on_closing)executes theon_closingfunction. - Inside the function, I write the first line which is
global StartInbecause I want to access the outer scope variable and want to change that (As you notice the fourth line of code isStartIn = 0). - The Second line of code inside the
on_closingfunction isStartIn = WhenInput(). Here I call theWhenInputfunction which is return the text value in the form ofinteger(int). - and, The Third line of code is
when.destroywhich is just destroy the window.
