Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the textvariable out of a Tkinter Entry widget?

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.

like image 294
Tekar Avatar asked Oct 27 '25 09:10

Tekar


1 Answers

To get any attribute of a widget, use cget:

print(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))
like image 132
Bryan Oakley Avatar answered Oct 28 '25 22:10

Bryan Oakley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!