Getting the textvariable out of a Tkinter Entry widget?

Tekar picture Tekar · Jan 31, 2013 · Viewed 7.8k times · Source

I'm trying to bind a function to my Tkinter root that reacts when the user presses return. Here's the code:

def returnPressed(event):
    print repr(event.widget)

master = Tk()

master.bind("<Return>", returnPressed)
myStringVar = StringVar(value="Foo")
myEntry = Entry(master, textvariable=myStringVar)
myEntry.grid()

master.mainloop()

This works, however now I need to get the StringVar variable of the Entry while in the returnPressed function.

I have the widget, but I can't get the variable object. I know how to get the variable content but I really need the object.

Answer

Bryan Oakley picture Bryan Oakley · Jan 31, 2013

To get any attribute of a widget, use cget:

print repr(event.widget.cget("textvariable"))

However, in this particular instance what you get back is the internal name of the stringvar rather than the stringvar itself, due to some implementation details. So, you'll have to find another way.

The easiest thing might be to pass the stringvar instance to the function that is called. You can do this with lambda or functools.partial. For example:

def returnPressed(event, v):
    ...
master.bind("<Return>",lambda event, v=myStringVar: returnPressed(event, v))