blob: 133c6fdb21686cf9ba0c919cd9384312bbf85761 [file] [log] [blame]
Steven M. Gavaf126bcb2001-10-26 06:49:14 +00001"""
2OptionMenu widget modified to allow dynamic menu reconfiguration
Steven M. Gavac034b472001-11-03 14:55:47 +00003and setting of highlightthickness
Steven M. Gavaf126bcb2001-10-26 06:49:14 +00004"""
Terry Jan Reedy62012fc2014-05-24 18:48:03 -04005from Tkinter import OptionMenu, _setit, Tk, StringVar, Button
6
Steven M. Gavac034b472001-11-03 14:55:47 +00007import copy
Terry Jan Reedy62012fc2014-05-24 18:48:03 -04008import re
Steven M. Gavaf126bcb2001-10-26 06:49:14 +00009
10class DynOptionMenu(OptionMenu):
11 """
Steven M. Gavac034b472001-11-03 14:55:47 +000012 unlike OptionMenu, our kwargs can include highlightthickness
Steven M. Gavaf126bcb2001-10-26 06:49:14 +000013 """
14 def __init__(self, master, variable, value, *values, **kwargs):
Steven M. Gavac034b472001-11-03 14:55:47 +000015 #get a copy of kwargs before OptionMenu.__init__ munges them
16 kwargsCopy=copy.copy(kwargs)
17 if 'highlightthickness' in kwargs.keys():
18 del(kwargs['highlightthickness'])
Steven M. Gavaf126bcb2001-10-26 06:49:14 +000019 OptionMenu.__init__(self, master, variable, value, *values, **kwargs)
Steven M. Gavac034b472001-11-03 14:55:47 +000020 self.config(highlightthickness=kwargsCopy.get('highlightthickness'))
Steven M. Gavaf126bcb2001-10-26 06:49:14 +000021 #self.menu=self['menu']
22 self.variable=variable
23 self.command=kwargs.get('command')
Kurt B. Kaiser6655e4b2002-12-31 16:03:23 +000024
Steven M. Gava41a85322001-10-29 08:05:34 +000025 def SetMenu(self,valueList,value=None):
Steven M. Gavaf126bcb2001-10-26 06:49:14 +000026 """
27 clear and reload the menu with a new set of options.
28 valueList - list of new options
Kurt B. Kaiser6655e4b2002-12-31 16:03:23 +000029 value - initial value to set the optionmenu's menubutton to
Steven M. Gavaf126bcb2001-10-26 06:49:14 +000030 """
31 self['menu'].delete(0,'end')
32 for item in valueList:
33 self['menu'].add_command(label=item,
34 command=_setit(self.variable,item,self.command))
Steven M. Gava41a85322001-10-29 08:05:34 +000035 if value:
36 self.variable.set(value)
Terry Jan Reedy62012fc2014-05-24 18:48:03 -040037
38def _dyn_option_menu(parent):
39 root = Tk()
40 root.title("Tets dynamic option menu")
41 var = StringVar(root)
42 width, height, x, y = list(map(int, re.split('[x+]', parent.geometry())))
43 root.geometry("+%d+%d"%(x, y + 150))
44 var.set("Old option set") #Set the default value
45 dyn = DynOptionMenu(root,var, "old1","old2","old3","old4")
46 dyn.pack()
47
48 def update():
49 dyn.SetMenu(["new1","new2","new3","new4"],value="new option set")
50
51 button = Button(root, text="Change option set", command=update)
52 button.pack()
53 root.mainloop()
54
55if __name__ == '__main__':
56 from idlelib.idle_test.htest import run
57 run(_dyn_option_menu)