Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 923
qwerty_so Avatar asked Nov 27 '25 03:11

qwerty_so


1 Answers

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()
like image 154
Victor Domingos Avatar answered Nov 28 '25 15:11

Victor Domingos