idanshmu
idanshmu

Reputation: 5271

Tkinter - variable to trace change in other variable

So I have this code snippet:

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)

which generates this UI:

enter image description here

Question

How do I trace changes in OptionMenuVar and update AgeVar based on the selected value?

I've read The Variable Classes. I guess I know how to trace changes in OptionMenuVar but I still don't know how to:

  1. detect the new value
  2. update AgeVar according to the new value

Upvotes: 0

Views: 1692

Answers (1)

idanshmu
idanshmu

Reputation: 5271

So this is the way to do it:

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))

Complete code

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))

All the credit to Marcin answer.

Upvotes: 2

Related Questions