[Tutor] Accessing an entry value input by the user

Alan Gauld alan.gauld at yahoo.co.uk
Sat Feb 11 12:52:30 EST 2017


On 11/02/17 15:28, Pooja Bhalode wrote:

> I am trying to create a label and an entry widget. I am not able to
> understand as to how to access the value input by the user in the entry
> widget.
> 
> Label(frame1, text = "Number of species:").grid(row=0, column = 1, sticky=W)
> entrynumberspecies = Entry(frame1)
> entrynumberspecies.grid(row=0, column = 2, sticky=W)
> 
> print entrynumberspecies.get()

You just accessed it, via the get() method. Did that not work?

> How can I make the entrynumberspecies store the value in once the user
> inputs it and then use that value for later part of my code? 

You can do it the way you did above using the get() method.

But you can also do what you did for the checkboxes - use
a StringVar and attach it to the Entry widget textvariable
attribute. That way the variable will reflect whats in
the Entry automatically and if you update the variable
it will update the Entry. (Personally I prefer to use
get() in most cases but many use the StringVar technique.)
See the example at the bottom...

> or print it for that matter.

You can print it as you did above or you can store it in
a variable and then print it or you can print the StringVar:

print myEntry.get()

myVar = MyEntry.get()
print myVar

entryVar = StringVar()
myEntry = Entry(.....textvariable=entryVar)
print entryVar.get()

Here is a minimal example:

################
from Tkinter import *

def show():
    print "entry says: " + e.get()
    print "Variable holds: " + v.get()

top = Tk()
v = StringVar()
e = Entry(top,textvariable=v)
e.pack()
Button(top,text="Set foobar", command=lambda : v.set("foobar")).pack()
Button(top,text="Show me", command=show).pack()

top.mainloop()
#################


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list