-2

i want to recover the real value entered by users to a variable using Tkinter. Here is my code

from Tkinter import *

master = Tk()
Label(master, text="real value 1").grid(row=0)
Label(master, text="real value 2").grid(row=1)

e1 = Entry(master)
e2 = Entry(master)

e1.grid(row=0, column=1)
e2.grid(row=1, column=1)

print e1.get()
x=e1.get()
mainloop( )

However my code can neither print the real value i have entred in the table nor assign this number to my variable x (a variable i would like to use outside tkinter). How can i get the value e1, e2 entered by users?

SC_thesard
  • 39
  • 1
  • 2
  • Possible duplicate of [Get contents of a Tkinter Entry widget](https://stackoverflow.com/questions/9815063/get-contents-of-a-tkinter-entry-widget) – Austin Apr 09 '18 at 15:46
  • 3
    You printed out the value *immediately* after creating the widget. When has the user had any possible chance to enter anything? You need to call `.get()` at some later time, after the user has indicated that they are done with their entry - commonly, this would be in a function specified by the `command=` option of a Button. – jasonharper Apr 09 '18 at 15:47
  • @theausome it is the first time i use tkinter......can anyone make a demonstration of my example? – SC_thesard Apr 09 '18 at 15:56
  • @jasonharper i have tried print e1.get() outside, but it still doesn't work.... – SC_thesard Apr 09 '18 at 15:58
  • @S.Cheng Did my answer work for you? Remember to accept it if it did. – scotty3785 Apr 11 '18 at 10:02

1 Answers1

1

As has been mentioned, you are getting the value of the entry widgets before the user has time to enter any text. A simple way to deal with this is to read the values after a user action such as pressing a button.

from Tkinter import *

def readValues():
    print(e1.get())
    print(e2.get())

master = Tk()
Label(master, text="real value 1").grid(row=0)
Label(master, text="real value 2").grid(row=1)

e1 = Entry(master)
e2 = Entry(master)

e1.grid(row=0, column=1)
e2.grid(row=1, column=1)

Button(master,text="Go",command=readValues).grid(row=2)

mainloop( )

You could also do this based on when the window is closed.

scotty3785
  • 6,763
  • 1
  • 25
  • 35