PascalVKooten
PascalVKooten

Reputation: 21433

Obtaining value of tkinter Entry field for using (locally) in a function

I am creating a GUI, and something is going on with the variables.

It starts with calculating a value theta, which when I click a button, gets passed to an Entry field (this is written in a function: thetaVar.set(CalcTheta(grensVar.get(), data[:,1], data[:,2]))).

thetaVar = IntVar()

def callbackTheta(name, index, mode):
    thetaValue = nGui.globalgetvar(name)
    nGui.globalsetvar(name, thetaValue)

wtheta = thetaVar.trace_variable('w', callbackTheta)
rtheta = thetaVar.trace_variable('r', callbackTheta)

entryTheta = Entry(textvariable=thetaVar).place(x=90, y=202)

This works (and I see the value in the Entry field), but when I later try to obtain this value, it does not work. I believe I tried everything:

thetaVar.get()   # with print, returns the integer 0, this is the initial value 
                 # that is displayed, even though at that moment it shows 0.4341.
thetaVar         # with print, returns 'PY_VAR3'
thetaValue       # with print, global value not defined
entryTheta.get() # AttributeError: 'NoneType' object has no attribute 'get'
rtheta           # print returns: 37430496callbackTheta

I do not understand where this value is stored and how I can use the value of the entry in another function. Even when I try any of these right after the actual .set, I cannot seem to print this specific value of the Entry right after.

Using tkinter and Python 3.3 on windows 8.

Upvotes: 1

Views: 2188

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385830

There are two ways to get the value of an entry widget:

  1. you call the get method on the widget, eg: the_widget.get()
  2. IF you have a textvariable assigned, you can call the get method on the textvariable, eg: the_variable.get()

For either of these to work, you must have a reference to either 1) the widget, or 2) the textvariable.

In your code you are making a common mistake, which is to combine widget creation and widget layout. This results in entryTheta being set to None.

When you do something like foo=bar().baz(), what gets stored in foo is the result of the final function, baz(). Thus, when you do entryTheta = Entry(textvariable=thetaVar).place(x=90, y=202), entryTheta is set to the result of the call to place which will always be None.

The simple solution is to call place in a separate statement (and you should also seriously reconsider the use of place -- pack and grid are much more powerful and will give you better resize behavior.)

Upvotes: 2

Related Questions