0

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
idanshmu
  • 5,061
  • 6
  • 46
  • 92
  • You can a `StringVar` object's `trace()` method to call some function whenever it's value is changed. In your case `OptionMenuVar.trace("w", mycallback)`. See [_The Variable Classes (BooleanVar, DoubleVar, IntVar, StringVar)_](http://effbot.org/tkinterbook/variable.htm). The `"w"` is the `mode` and means call when "written". – martineau Apr 08 '15 at 06:59
  • Yes. Already aware of that approach. Just don't know how to apply it :) – idanshmu Apr 08 '15 at 07:02
  • Just figured it out... – idanshmu Apr 08 '15 at 07:06
  • Write a function that when called gets the current value of `OptionMenuVar` and sets the value of `AgeVar`. – martineau Apr 08 '15 at 07:06
  • It's difficult to read your code because you're not following [PEP 8 - Style Guide for Python Code](https://www.python.org/dev/peps/pep-0008/) with regards to your variable names, which all look like class names because of their use of CapWords, (aka CamelCase). – martineau Apr 08 '15 at 07:12
  • Hope you'll cut me some slack this time. the main thing is the we were able to trace changes is one variable and apply them to another. – idanshmu Apr 08 '15 at 07:18

1 Answers1

2

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.

Community
  • 1
  • 1
idanshmu
  • 5,061
  • 6
  • 46
  • 92