Home > Back-end >  How to stop Tkinter OptionMenu from changing value?
How to stop Tkinter OptionMenu from changing value?

Time:07-16

I want the OptionMenu to have a title/text that never changes.

from tkinter import *

root = Tk()

def choose(*args):
    print("Choose something")
    variable.set("Choose something")

options = ["Something1", "Something2", "Something3"]
variable = StringVar()
variable.set("Choose something")
variable.trace("w", choose)
om = OptionMenu(root, variable, *options)
om.grid(row=0, column=0)

root.mainloop()

The problem is that the text changes to the selected value and changes back to the default value "Choose something" only when I hover the OptionMenu again.

CodePudding user response:

The solution is from @jasonharper

Modifying a Var within a write trace on the same Var is problematic - other write traces on the Var (such as the one that updates the OptionMenu) are suppressed, as this would otherwise result in an infinite recursion. You need to delay the modification until after the original write has completed - root.after(1, variable.set, "Choose something") should work, although I think you'll need to add a check to make sure that the value wasn't "Choose something" already.

CodePudding user response:

  1. Don't use *arg in the choose function.
  2. Line 6: Replace variables.set with variables.get().
  3. Line 12 made use of an index rather than a string.
  4. In line 13, I comment out.
  5. In line 14, I added command=choose

Try this:

from tkinter import *

root = Tk()

def choose(choice):
    choice = variable.get()
    print(choice)


options = ["Something1", "Something2", "Something3"]
variable = StringVar()
variable.set(options[2])
#variable.trace("w", choose)
om = OptionMenu(root, variable, *options, command=choose)
om.grid(row=0, column=0)

root.mainloop()
  • Related