0

I would like to ask something that I think it may be very simple, but I can not get it!

I am using tkinter in python, and I am trying to build an entry. The text of this entry should be stored in a variable (I called it "s"). BUT, I want also that this widget works dynamicly. For example. I start the program, I introduce some text from the keyboard, and it is stored in "s", then I want to introduce something different, and now what the "s" variable stores is the new introduced text, not the old one. I wrote this code but my "s" variable always stores the original text.

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

e = Entry(root)
e.pack()

e.delete(0, END)
e.insert(0, "a default value")
s = e.get()

print s
root.mainloop() 

To introduce a text, Do I have to write it in the box, and then press Enter? Thanks a lot Pablo

pablo casanovas
  • 128
  • 1
  • 2
  • 15

1 Answers1

0

The text is entered during the mainloop. Use a callback (with a Button widget for example) to get your text.

For example, here is a callback using a Button :

from tkinter import *

def print_input(entry):
    print entry.get()

root = Tk()
root.geometry("250x250")
e = Entry(root)
e.pack()

b = Button(root, text="Print my input", command=lambda e=e: print_input(e))
b.pack()

root.mainloop()

You can also bind the <return> key for all your window by using the following line :

def func(event):
    print("You hit return.")
root.bind('<Return>', func)

Here are some interesting ways to do it : Can't figure out how to bind the enter key to a function in tkinter

Community
  • 1
  • 1
FunkySayu
  • 7,641
  • 10
  • 38
  • 61