0

I tried updating the value of an OptionMenu in Tkinter but was unable to do so.

I updated the value of the (text)variable passed to the OptionMenu but that doesn't directly update it without hovering over it (or after a while). I even tried passing different configs (like text, value, ...) but those parameters either didn't exist or didn't directly update the value.

Program Code:

    self.aPLabel = Label(self, text="Action to be performed", anchor='w')
    self.aPLabel.grid(row=7, column=0, sticky=W)
    self.aPVar = StringVar(self, "Play Buzzer")
    self.aPBox = OptionMenu(self, self.aPVar, "Exit on done", "Play Buzzer", "Execute script")
    self.aPBox.grid(row=7, column=1, sticky=W+E)
    tmp=None
    def callback(*args):
      if self.aPVar.get()=="Execute script":
        filename = askopenfilename(filetypes=[("Python Script (*.py)", ".py")])
        if filename:
          self.aPVar.set(f"Execute script: {filename}")
          self.aPBox.configure()
          tmp = self.aPVar.get()
        else:
          pass
    self.aPVar.trace("w", callback)
  • There's already a question on this site about this. You should do a search and try to find it. – Bryan Oakley Jun 18 '21 at 16:17
  • I really tried finding it but was unable it find it. That's why ended up drafting this question. I'm really sorry for the inconvenience but could you please share the link for the same. – Shyam Singh Jun 18 '21 at 16:25
  • Have you looked at [Updating OptionMenu from List](https://stackoverflow.com/questions/28412496/updating-optionmenu-from-list)? – martineau Jun 18 '21 at 16:34
  • You are writing a new value to your StringVar from within a write trace on that very StringVar - a time during which write traces are inhibited (this would be an infinite recursion, otherwise). So the write trace that updates the widget from the Var is inhibited as well. (I'm not sure it's valid to set an OptionMenu's Var to something that isn't one of its defined options, anyway.) – jasonharper Jun 18 '21 at 16:35
  • @jasonharper Thanks a lot for the accurate description of the problem here. I have added used `self.after(0, lambda: self.aPVar.set(f"Execute script: {filename}"))` instead of just `self.aPVar.set(f"Execute script: {filename}"))` and that has solved the issue. Thanks a lot for the help! – Shyam Singh Jun 18 '21 at 16:41

0 Answers0