Home > OS >  How to get the text inserted in a tkinter text box?
How to get the text inserted in a tkinter text box?

Time:04-28

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.

  1. Your main root name which is when = tk.Tk() and the text input name is the same which is when.
  2. 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.

  1. First I change the same variable name.
  2. 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 pass on_closing as a parameter. This is because when someone tries to exit or destroy the window the protocol("WM_DELETE_WINDOW", on_closing) executes the on_closing function.
  3. Inside the function, I write the first line which is global StartIn because I want to access the outer scope variable and want to change that (As you notice the fourth line of code is StartIn = 0).
  4. The Second line of code inside the on_closing function is StartIn = WhenInput(). Here I call the WhenInput function which is return the text value in the form of integer(int).
  5. and, The Third line of code is when.destroy which is just destroy the window.
  • Related