Search code examples
pythonpython-2.7tkintertkinter-entry

Transforming a Tkinter entry to variable


I can't get an entry value and make it a usable variable for the rest of my code, this part is only able to create a variable z, but it ends up empty, this is my forth try on a different approach without good result.

The entry.get() returns nothing, I need it to return a string.

from Tkinter import *

class Application(Frame):
    def __init__(self, master=None):
        Frame.__init__(self,master)
        self.grid()
        self.initialize()        

    def initialize(self):

        self.btn1 = Button(self, text = 'Ok', command=retrieve_input)
        self.btn1.grid()


def retrieve_input():
    print 'Input value => %s' %entry.get()     

root = Tk()
root.title('Teste')
root.geometry('200x100')
entry = Entry(root)
entry.grid(column=0,row=0)


entry.focus()                                    
entry.bind('<Return>', (lambda event: retrieve_input()))  
z=entry.get()

app = Application(root)
root.mainloop()

Solution

  • You need to call:

    z = entry.get()
    

    whenever you want z to be what's written in entry. As in replace retrieve_input with:

    def retrieve_input():
        global z
        z = entry.get()
        print 'Input value => %s' %z
    

    for example.