Tkinter - 用于跟踪其他变量的变量的变量

时间:2015-04-08 06:39:10

标签: python callback tkinter observers

所以我有这段代码:

for p in self.ProductNames:
    OptionMenuVar = StringVar()
    menu = OptionMenu(self.FrameProducts, OptionMenuVar, *self.ProductNames)
    OptionMenuVar.set(p)

    AgeVar = StringVar()
    AgeEntry = Entry(self.FrameProducts,width=15,textvariable=AgeVar,state="readonly",justify=CENTER)

生成此UI:

enter image description here

问题

如何跟踪OptionMenuVar中的更改并根据所选值更新AgeVar

我看过The Variable Classes。我想我知道如何追踪OptionMenuVar中的变化,但我仍然不知道如何:

  1. 检测新值
  2. 根据新值
  3. 更新AgeVar

1 个答案:

答案 0 :(得分:2)

所以这是做到这一点的方法:

def OnOptionMenuChnage(omv,av, *pargs):
    print omv.get(), av.get()
    # do more. set av value based on omv value

OptionMenuVar.trace("w", lambda *pargs: OnOptionMenuChnage(OptionMenuVar,AgeVar, *pargs))

完整代码

for p in self.ProductNames:
    OptionMenuVar = StringVar()
    menu = OptionMenu(self.FrameProducts, OptionMenuVar, *self.ProductNames)
    OptionMenuVar.set(p)

    AgeVar = StringVar()
    AgeEntry = Entry(self.FrameProducts,width=15,textvariable=AgeVar,state="readonly",justify=CENTER)

    def OnOptionMenuChnage(omv,av, *pargs):
        print omv.get(), av.get()
        # do more. set av value based on omv value

    OptionMenuVar.trace("w", lambda *pargs: OnOptionMenuChnage(OptionMenuVar,AgeVar, *pargs))

所有归功于Marcin answer