1""" 2OptionMenu widget modified to allow dynamic menu reconfiguration 3and setting of highlightthickness 4""" 5import copy 6 7from tkinter import OptionMenu, _setit, StringVar, Button 8 9class DynOptionMenu(OptionMenu): 10 """ 11 unlike OptionMenu, our kwargs can include highlightthickness 12 """ 13 def __init__(self, master, variable, value, *values, **kwargs): 14 # TODO copy value instead of whole dict 15 kwargsCopy=copy.copy(kwargs) 16 if 'highlightthickness' in list(kwargs.keys()): 17 del(kwargs['highlightthickness']) 18 OptionMenu.__init__(self, master, variable, value, *values, **kwargs) 19 self.config(highlightthickness=kwargsCopy.get('highlightthickness')) 20 #self.menu=self['menu'] 21 self.variable=variable 22 self.command=kwargs.get('command') 23 24 def SetMenu(self,valueList,value=None): 25 """ 26 clear and reload the menu with a new set of options. 27 valueList - list of new options 28 value - initial value to set the optionmenu's menubutton to 29 """ 30 self['menu'].delete(0,'end') 31 for item in valueList: 32 self['menu'].add_command(label=item, 33 command=_setit(self.variable,item,self.command)) 34 if value: 35 self.variable.set(value) 36 37def _dyn_option_menu(parent): # htest # 38 from tkinter import Toplevel # + StringVar, Button 39 40 top = Toplevel(parent) 41 top.title("Tets dynamic option menu") 42 x, y = map(int, parent.geometry().split('+')[1:]) 43 top.geometry("200x100+%d+%d" % (x + 250, y + 175)) 44 top.focus_set() 45 46 var = StringVar(top) 47 var.set("Old option set") #Set the default value 48 dyn = DynOptionMenu(top,var, "old1","old2","old3","old4") 49 dyn.pack() 50 51 def update(): 52 dyn.SetMenu(["new1","new2","new3","new4"], value="new option set") 53 button = Button(top, text="Change option set", command=update) 54 button.pack() 55 56if __name__ == '__main__': 57 from idlelib.idle_test.htest import run 58 run(_dyn_option_menu) 59