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