【问题标题】:Obtaining value of tkinter Entry field for using (locally) in a function获取 tkinter Entry 字段的值以在函数中(本地)使用
【发布时间】:2013-03-18 22:12:52
【问题描述】:

我正在创建一个 GUI,变量正在发生变化。

它从计算一个值 theta 开始,当我单击一个按钮时,它被传递到一个 Entry 字段(这写在一个函数中: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)

这行得通(并且我在 Entry 字段中看到了该值),但是当我稍后尝试获取此值时,它不起作用。 我相信我什么都试过了:

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。

【问题讨论】:

  • 我列出了我尝试过的东西。请看第二段代码。

标签: python tkinter


【解决方案1】:

有两种方法可以获取条目小部件的值:

  1. 您在小部件上调用get 方法,例如:the_widget.get()
  2. 如果你分配了一个文本变量,你可以在这个文本变量上调用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 -- packgrid 更强大,并且会给您更好的调整大小行为。 )

【讨论】:

  • 哇哦!非常感谢!我永远不会猜到。请注意,我现在可以从小部件中获取值,但是 thetaVar.get() 仍然打印为 0,而 entryTheta.get() 确实打印到正确的值
  • 我现在使用 place 是为了方便显示第一个版本。我假设我将不得不重新设计整个布局,然后重新考虑打包和网格。谢谢。
猜你喜欢
  • 2021-08-29
  • 1970-01-01
  • 2020-11-28
  • 1970-01-01
  • 2022-06-29
  • 2018-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多