select_combobox.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. from tkinter import ttk
  2. class SelectCombobox(ttk.Combobox):
  3. def __init__(self, master=None, **kwargs):
  4. selected_values = kwargs.pop("selected_values", [])
  5. values = kwargs.pop("values", [])
  6. command = kwargs.pop("command", None)
  7. super().__init__(master, **kwargs)
  8. self.selected_values = selected_values
  9. self.values = values
  10. self.command = command
  11. self["values"] = self.values
  12. self.bind("<<ComboboxSelected>>", self.on_select)
  13. self.bind("<FocusOut>", self.on_text_change)
  14. self.update_values()
  15. def on_select(self, event):
  16. selected_value = self.get().strip()
  17. self.update_selected_values(selected_value)
  18. self.update_values()
  19. if self.command:
  20. self.command(event)
  21. def on_text_change(self, event):
  22. text_value = self.get().strip()
  23. value_list = [value.strip() for value in text_value.split(",") if value.strip()]
  24. self.selected_values = [
  25. value for value in self.selected_values if value in value_list
  26. ]
  27. for value in value_list:
  28. if value in self.values and value not in self.selected_values:
  29. self.selected_values.append(value)
  30. self.update_values()
  31. if self.command:
  32. self.command(event)
  33. def update_selected_values(self, value):
  34. if value in self.selected_values:
  35. self.selected_values.remove(value)
  36. else:
  37. self.selected_values.append(value)
  38. def update_values(self):
  39. display_text = ",".join(self.selected_values)
  40. self.set(display_text)