How to get the input from the Tkinter Text Widget?
To get Tkinter input from the text box, you must add a few more attributes to the normal .get()
function. If we have a text box myText_Box
, then this is the method for retrieving its input.
def retrieve_input():
input = self.myText_Box.get("1.0",END)
The first part, "1.0"
means that the input should be read from line one, character zero (ie: the very first character). END
is an imported constant which is set to the string "end"
. The END
part means to read until the end of the text box is reached. The only issue with this is that it actually adds a newline to our input. So, in order to fix it we should change END
to end-1c
(Thanks Bryan Oakley) The -1c
deletes 1 character, while -2c
would mean delete two characters, and so on.
def retrieve_input():
input = self.myText_Box.get("1.0",'end-1c')
To get Tkinter input from the text box in python 3 the complete student level program used by me is as under:
#Imports all (*) classes,
#atributes, and methods of tkinter into the
#current workspace
from tkinter import *
#***********************************
#Creates an instance of the class tkinter.Tk.
#This creates what is called the "root" window. By conventon,
#the root window in Tkinter is usually called "root",
#but you are free to call it by any other name.
root = Tk()
root.title('how to get text from textbox')
#**********************************
mystring = StringVar()
####define the function that the signup button will do
def getvalue():
## print(mystring.get())
#*************************************
Label(root, text="Text to get").grid(row=0, sticky=W) #label
Entry(root, textvariable = mystring).grid(row=0, column=1, sticky=E) #entry textbox
WSignUp = Button(root, text="print text", command=getvalue).grid(row=3, column=0, sticky=W) #button
############################################
# executes the mainloop (that is, the event loop) method of the root
# object. The mainloop method is what keeps the root window visible.
# If you remove the line, the window created will disappear
# immediately as the script stops running. This will happen so fast
# that you will not even see the window appearing on your screen.
# Keeping the mainloop running also lets you keep the
# program running until you press the close buton
root.mainloop()
Here is how I did it with python 3.5.2:
from tkinter import *
root=Tk()
def retrieve_input():
inputValue=textBox.get("1.0","end-1c")
print(inputValue)
textBox=Text(root, height=2, width=10)
textBox.pack()
buttonCommit=Button(root, height=1, width=10, text="Commit",
command=lambda: retrieve_input())
#command=lambda: retrieve_input() >>> just means do this when i press the button
buttonCommit.pack()
mainloop()
with that, when i typed "blah blah" in the text widget and pressed the button, whatever i typed got printed out. So i think that is the answer for storing user input from Text widget to variable.