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