qwerty_so
qwerty_so

Reputation: 36305

Changing the selected item of an OptionMenu programmatically

I have defined a simple OptionMenu like

import Tkinter as tk

optionList = ('a', 'b', 'c')
v = tk.StringVar()
v.set(optionList[0])
om = tk.OptionMenu(self, v, *optionList)

This list will appear with a as default which is fine. But there are also command buttons defined which eventually need to alter this to show another of the available options (say b). How can this be achieved?

Upvotes: 3

Views: 6762

Answers (1)

Victor Domingos
Victor Domingos

Reputation: 1083

You already found a way to set a default value and change it. You have the v variable associated to that OptionMenu widget. If at any time you change the value of that variable again, it will update your widget:

import tkinter as tk

root = tk.Tk()
optionList = ('a', 'b', 'c')
v = tk.StringVar()
v.set(optionList[0])  # Here is the initially selected value
om = tk.OptionMenu(root, v, *optionList)
om.pack()

v.set(optionList[2]) # This one will be the final selected value 
root.mainloop()

Upvotes: 7

Related Questions