在函数中获取tkinter Entry字段的值
我正在创建一个图形用户界面(GUI),但是在变量方面遇到了一些问题。
一开始,我要计算一个叫做theta的值,当我点击一个按钮时,这个值会被传递到一个输入框里(这个过程是在一个函数中完成的: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)
这个过程是有效的(我可以在输入框中看到这个值),但是当我后来想要获取这个值时,却无法成功。我觉得我尝试了所有的方法:
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
我不明白这个值存储在哪里,以及如何在另一个函数中使用输入框的值。即使我在调用.set
之后立刻尝试,也无法打印出输入框中这个特定的值。
我在Windows 8上使用的是tkinter和Python 3.3。
1 个回答
2
获取一个输入框的值有两种方法:
- 你可以直接调用这个输入框的
get
方法,比如说:the_widget.get()
- 如果你有一个和输入框关联的文本变量,你也可以调用这个文本变量的
get
方法,比如:the_variable.get()
要让这两种方法都能用,你必须有对 1) 输入框,或者 2) 文本变量 的引用。
在你的代码中,你犯了一个常见的错误,就是把创建输入框和布局放在了一起。这导致 entryTheta
被设置为 None
。
当你写类似 foo=bar().baz()
的代码时,存储在 foo
中的是最后一个函数的结果,也就是 baz()
的结果。因此,当你写 entryTheta = Entry(textvariable=thetaVar).place(x=90, y=202)
时,entryTheta
实际上被设置为调用 place
的结果,而这个结果总是 None
。
简单的解决办法是把 place
放在一个单独的语句中(而且你也应该认真考虑一下使用 place
-- pack
和 grid
更强大,能让你的界面在调整大小时表现得更好。)