2

I'm trying to get the value of an entry in tkinter!

when I print the value directly ( for example print(e2.get() ) it works well, but when I put this into a variable and then print it ( for example x = e2.get() print(x) ) it's not working!

here is the code:

import tkinter as tk

def show_entry_fields():
    print("First Name: %s\n Last Name: %s" % (x, e2.get()))

master = tk.Tk()
tk.Label(master, 
         text="First Name").grid(row=0)
tk.Label(master, 
         text="Last Name").grid(row=1)

e1 = tk.Entry(master)
e2 = tk.Entry(master)

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

x = e1.get()

tk.Button(master, 
          text='Quit', 
          command=master.quit).grid(row=3, 
                                    column=0, 
                                    sticky=tk.W, 
                                    pady=4)
tk.Button(master, 
          text='Show', command=show_entry_fields).grid(row=3, 
                                                       column=1, 
                                                       sticky=tk.W, 
                                                       pady=4)

tk.mainloop()

I need to put the entry value in a variable, how can I do it?

f ebrahimi
  • 25
  • 4
  • which line is in error ? `x = e1.get()` ? – Hippolyte BRINGER Jun 04 '19 at 14:35
  • Why do you think it's not working? What does "not working" mean? Do you get an error? Does it get the wrong value? – Bryan Oakley Jun 04 '19 at 14:43
  • Are you aware that when you do `x=e1.get()`, it gets the value at that moment in time? `x` won't be updated later if the value in `e1` changes. – Bryan Oakley Jun 04 '19 at 14:44
  • there is no error, just in line `print("First Name: %s\n Last Name: %s" % (x, e2.get()))` `e2.get()` going to print but x do not! Instead of x, an empty content is printed! @HippolyteBRINGER @BryanOakley – f ebrahimi Jun 04 '19 at 14:47

1 Answers1

1

It's simple if you understand :

When the code pass by x = e1.get(), e1 equals just "".

After your write in e1 and call the def show_entry_fields when you click in the button.

But x is always equals to "". And e1.get() get the text in the e1.

So it's why print(x) equals "" because you pass by the line x = e1.get() just one time !

Hippolyte BRINGER
  • 792
  • 1
  • 8
  • 30