dynoption.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. """
  2. OptionMenu widget modified to allow dynamic menu reconfiguration
  3. and setting of highlightthickness
  4. """
  5. from tkinter import OptionMenu, _setit, StringVar, Button
  6. class DynOptionMenu(OptionMenu):
  7. """Add SetMenu and highlightthickness to OptionMenu.
  8. Highlightthickness adds space around menu button.
  9. """
  10. def __init__(self, master, variable, value, *values, **kwargs):
  11. highlightthickness = kwargs.pop('highlightthickness', None)
  12. OptionMenu.__init__(self, master, variable, value, *values, **kwargs)
  13. self['highlightthickness'] = highlightthickness
  14. self.variable = variable
  15. self.command = kwargs.get('command')
  16. def SetMenu(self,valueList,value=None):
  17. """
  18. clear and reload the menu with a new set of options.
  19. valueList - list of new options
  20. value - initial value to set the optionmenu's menubutton to
  21. """
  22. self['menu'].delete(0,'end')
  23. for item in valueList:
  24. self['menu'].add_command(label=item,
  25. command=_setit(self.variable,item,self.command))
  26. if value:
  27. self.variable.set(value)
  28. def _dyn_option_menu(parent): # htest #
  29. from tkinter import Toplevel # + StringVar, Button
  30. top = Toplevel(parent)
  31. top.title("Test dynamic option menu")
  32. x, y = map(int, parent.geometry().split('+')[1:])
  33. top.geometry("200x100+%d+%d" % (x + 250, y + 175))
  34. top.focus_set()
  35. var = StringVar(top)
  36. var.set("Old option set") #Set the default value
  37. dyn = DynOptionMenu(top, var, "old1","old2","old3","old4",
  38. highlightthickness=5)
  39. dyn.pack()
  40. def update():
  41. dyn.SetMenu(["new1","new2","new3","new4"], value="new option set")
  42. button = Button(top, text="Change option set", command=update)
  43. button.pack()
  44. if __name__ == '__main__':
  45. # Only module without unittests because of intention to replace.
  46. from idlelib.idle_test.htest import run
  47. run(_dyn_option_menu)