Search code examples
pythontkintertkinter-text

How do you grab the Text widget data from Tkinter in order to freely use the data?


I am trying to make use of the input text data that is entered through Tkinter's Text widget, the same way one would be able to use the data, it if the data was entered using the input() method in python.

Here is my sample code:

root=Tk()
root.geometry("750x250")


def retrieve_input():
    input_value = textBox.get("1.0","end-1c")
    print(input_value)


textBox = Text(root, height=7, width=50)
textBox.pack()
buttonCommit = Button(root, height=1, width=10, text="Commit",
                      command=lambda: retrieve_input())

buttonCommit.pack()

mainloop()

My issue is that I can see the values printed on the terminal, when I enter something and click the button, but I am not be able to, for instance, loop over the retrieve_input() function. Doing a return input_value doesn't really result in any output when I loop over the function, using a for loop.

In Short I would like to be able to do something like the following:

    #.....
    def retrieve_input():
        input_value = textBox.get("1.0","end-1c")
        print(input_value)
        return input_value
    
    for a in retrive_input():
       print(a)
   #.....

This is Just an example. It could be anything that allows me to use the content data that I enter through Tkinter.

I read somewhere that you somehow need an event handler to run at the appropriate time and capture the data but no idea how that's supposed to be implemented since no sample code was provided.


Solution

  • The only thing you need to do is a) make sure that retrieve_input returns the data, and b) make sure that the code that iterates over it doesn't run until the user has a chance to enter some data.

    from tkinter import *
    
    root=Tk()
    root.geometry("750x250")
    
    
    def retrieve_input():
        input_value = textBox.get("1.0","end-1c")
        return input_value
    
    
    def process_input():
        for a in retrieve_input():
            print(a)
    
    textBox = Text(root, height=7, width=50)
    textBox.pack()
    buttonCommit = Button(root, height=1, width=10, text="Commit",
                          command=process_input)
    buttonCommit.pack()
    
    mainloop()