ctk_combobox.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. import tkinter
  2. import sys
  3. import copy
  4. from typing import Union, Tuple, Callable, List, Optional, Any
  5. from .core_widget_classes import DropdownMenu
  6. from .core_rendering import CTkCanvas
  7. from .theme import ThemeManager
  8. from .core_rendering import DrawEngine
  9. from .core_widget_classes import CTkBaseClass
  10. from .font import CTkFont
  11. class CTkComboBox(CTkBaseClass):
  12. """
  13. Combobox with dropdown menu, rounded corners, border, variable support.
  14. For detailed information check out the documentation.
  15. """
  16. def __init__(self,
  17. master: Any,
  18. width: int = 140,
  19. height: int = 28,
  20. corner_radius: Optional[int] = None,
  21. border_width: Optional[int] = None,
  22. bg_color: Union[str, Tuple[str, str]] = "transparent",
  23. fg_color: Optional[Union[str, Tuple[str, str]]] = None,
  24. border_color: Optional[Union[str, Tuple[str, str]]] = None,
  25. button_color: Optional[Union[str, Tuple[str, str]]] = None,
  26. button_hover_color: Optional[Union[str, Tuple[str, str]]] = None,
  27. dropdown_fg_color: Optional[Union[str, Tuple[str, str]]] = None,
  28. dropdown_hover_color: Optional[Union[str, Tuple[str, str]]] = None,
  29. dropdown_text_color: Optional[Union[str, Tuple[str, str]]] = None,
  30. text_color: Optional[Union[str, Tuple[str, str]]] = None,
  31. text_color_disabled: Optional[Union[str, Tuple[str, str]]] = None,
  32. font: Optional[Union[tuple, CTkFont]] = None,
  33. dropdown_font: Optional[Union[tuple, CTkFont]] = None,
  34. values: Optional[List[str]] = None,
  35. state: str = tkinter.NORMAL,
  36. hover: bool = True,
  37. variable: Union[tkinter.Variable, None] = None,
  38. command: Union[Callable[[str], Any], None] = None,
  39. justify: str = "left",
  40. **kwargs):
  41. # transfer basic functionality (_bg_color, size, __appearance_mode, scaling) to CTkBaseClass
  42. super().__init__(master=master, bg_color=bg_color, width=width, height=height, **kwargs)
  43. # shape
  44. self._corner_radius = ThemeManager.theme["CTkComboBox"]["corner_radius"] if corner_radius is None else corner_radius
  45. self._border_width = ThemeManager.theme["CTkComboBox"]["border_width"] if border_width is None else border_width
  46. # color
  47. self._fg_color = ThemeManager.theme["CTkComboBox"]["fg_color"] if fg_color is None else self._check_color_type(fg_color)
  48. self._border_color = ThemeManager.theme["CTkComboBox"]["border_color"] if border_color is None else self._check_color_type(border_color)
  49. self._button_color = ThemeManager.theme["CTkComboBox"]["button_color"] if button_color is None else self._check_color_type(button_color)
  50. self._button_hover_color = ThemeManager.theme["CTkComboBox"]["button_hover_color"] if button_hover_color is None else self._check_color_type(button_hover_color)
  51. self._text_color = ThemeManager.theme["CTkComboBox"]["text_color"] if text_color is None else self._check_color_type(text_color)
  52. self._text_color_disabled = ThemeManager.theme["CTkComboBox"]["text_color_disabled"] if text_color_disabled is None else self._check_color_type(text_color_disabled)
  53. # font
  54. self._font = CTkFont() if font is None else self._check_font_type(font)
  55. if isinstance(self._font, CTkFont):
  56. self._font.add_size_configure_callback(self._update_font)
  57. # callback and hover functionality
  58. self._command = command
  59. self._variable = variable
  60. self._state = state
  61. self._hover = hover
  62. if values is None:
  63. self._values = ["CTkComboBox"]
  64. else:
  65. self._values = values
  66. self._dropdown_menu = DropdownMenu(master=self,
  67. values=self._values,
  68. command=self._dropdown_callback,
  69. fg_color=dropdown_fg_color,
  70. hover_color=dropdown_hover_color,
  71. text_color=dropdown_text_color,
  72. font=dropdown_font)
  73. # configure grid system (1x1)
  74. self.grid_rowconfigure(0, weight=1)
  75. self.grid_columnconfigure(0, weight=1)
  76. self._canvas = CTkCanvas(master=self,
  77. highlightthickness=0,
  78. width=self._apply_widget_scaling(self._desired_width),
  79. height=self._apply_widget_scaling(self._desired_height))
  80. self.draw_engine = DrawEngine(self._canvas)
  81. self._entry = tkinter.Entry(master=self,
  82. state=self._state,
  83. width=1,
  84. bd=0,
  85. justify=justify,
  86. highlightthickness=0,
  87. font=self._apply_font_scaling(self._font))
  88. self._create_grid()
  89. self._create_bindings()
  90. self._draw() # initial draw
  91. if self._variable is not None:
  92. self._entry.configure(textvariable=self._variable)
  93. # insert default value
  94. if self._variable is None:
  95. if len(self._values) > 0:
  96. self._entry.insert(0, self._values[0])
  97. else:
  98. self._entry.insert(0, "CTkComboBox")
  99. def _create_bindings(self, sequence: Optional[str] = None):
  100. """ set necessary bindings for functionality of widget, will overwrite other bindings """
  101. if sequence is None:
  102. self._canvas.tag_bind("right_parts", "<Enter>", self._on_enter)
  103. self._canvas.tag_bind("dropdown_arrow", "<Enter>", self._on_enter)
  104. self._canvas.tag_bind("right_parts", "<Leave>", self._on_leave)
  105. self._canvas.tag_bind("dropdown_arrow", "<Leave>", self._on_leave)
  106. self._canvas.tag_bind("right_parts", "<Button-1>", self._clicked)
  107. self._canvas.tag_bind("dropdown_arrow", "<Button-1>", self._clicked)
  108. def _create_grid(self):
  109. self._canvas.grid(row=0, column=0, rowspan=1, columnspan=1, sticky="nsew")
  110. left_section_width = self._current_width - self._current_height
  111. self._entry.grid(row=0, column=0, rowspan=1, columnspan=1, sticky="ew",
  112. padx=(max(self._apply_widget_scaling(self._corner_radius), self._apply_widget_scaling(3)),
  113. max(self._apply_widget_scaling(self._current_width - left_section_width + 3), self._apply_widget_scaling(3))),
  114. pady=self._apply_widget_scaling(self._border_width))
  115. def _set_scaling(self, *args, **kwargs):
  116. super()._set_scaling(*args, **kwargs)
  117. # change entry font size and grid padding
  118. self._entry.configure(font=self._apply_font_scaling(self._font))
  119. self._create_grid()
  120. self._canvas.configure(width=self._apply_widget_scaling(self._desired_width),
  121. height=self._apply_widget_scaling(self._desired_height))
  122. self._draw(no_color_updates=True)
  123. def _set_dimensions(self, width: int = None, height: int = None):
  124. super()._set_dimensions(width, height)
  125. self._canvas.configure(width=self._apply_widget_scaling(self._desired_width),
  126. height=self._apply_widget_scaling(self._desired_height))
  127. self._draw()
  128. def _update_font(self):
  129. """ pass font to tkinter widgets with applied font scaling and update grid with workaround """
  130. self._entry.configure(font=self._apply_font_scaling(self._font))
  131. # Workaround to force grid to be resized when text changes size.
  132. # Otherwise grid will lag and only resizes if other mouse action occurs.
  133. self._canvas.grid_forget()
  134. self._canvas.grid(row=0, column=0, rowspan=1, columnspan=1, sticky="nsew")
  135. def destroy(self):
  136. if isinstance(self._font, CTkFont):
  137. self._font.remove_size_configure_callback(self._update_font)
  138. super().destroy()
  139. def _draw(self, no_color_updates=False):
  140. super()._draw(no_color_updates)
  141. left_section_width = self._current_width - self._current_height
  142. requires_recoloring = self.draw_engine.draw_rounded_rect_with_border_vertical_split(self._apply_widget_scaling(self._current_width),
  143. self._apply_widget_scaling(self._current_height),
  144. self._apply_widget_scaling(self._corner_radius),
  145. self._apply_widget_scaling(self._border_width),
  146. self._apply_widget_scaling(left_section_width))
  147. requires_recoloring_2 = self.draw_engine.draw_dropdown_arrow(self._apply_widget_scaling(self._current_width - (self._current_height / 2)),
  148. self._apply_widget_scaling(self._current_height / 2),
  149. self._apply_widget_scaling(self._current_height / 3))
  150. if no_color_updates is False or requires_recoloring or requires_recoloring_2:
  151. self._canvas.configure(bg=self._apply_appearance_mode(self._bg_color))
  152. self._canvas.itemconfig("inner_parts_left",
  153. outline=self._apply_appearance_mode(self._fg_color),
  154. fill=self._apply_appearance_mode(self._fg_color))
  155. self._canvas.itemconfig("border_parts_left",
  156. outline=self._apply_appearance_mode(self._border_color),
  157. fill=self._apply_appearance_mode(self._border_color))
  158. self._canvas.itemconfig("inner_parts_right",
  159. outline=self._apply_appearance_mode(self._button_color),
  160. fill=self._apply_appearance_mode(self._button_color))
  161. self._canvas.itemconfig("border_parts_right",
  162. outline=self._apply_appearance_mode(self._button_color),
  163. fill=self._apply_appearance_mode(self._button_color))
  164. self._entry.configure(bg=self._apply_appearance_mode(self._fg_color),
  165. fg=self._apply_appearance_mode(self._text_color),
  166. readonlybackground=self._apply_appearance_mode(self._fg_color),
  167. disabledbackground=self._apply_appearance_mode(self._fg_color),
  168. disabledforeground=self._apply_appearance_mode(self._text_color_disabled),
  169. highlightcolor=self._apply_appearance_mode(self._fg_color),
  170. insertbackground=self._apply_appearance_mode(self._text_color))
  171. if self._state == tkinter.DISABLED:
  172. self._canvas.itemconfig("dropdown_arrow",
  173. fill=self._apply_appearance_mode(self._text_color_disabled))
  174. else:
  175. self._canvas.itemconfig("dropdown_arrow",
  176. fill=self._apply_appearance_mode(self._text_color))
  177. def _open_dropdown_menu(self):
  178. self._dropdown_menu.open(self.winfo_rootx(),
  179. self.winfo_rooty() + self._apply_widget_scaling(self._current_height + 0))
  180. def configure(self, require_redraw=False, **kwargs):
  181. if "corner_radius" in kwargs:
  182. self._corner_radius = kwargs.pop("corner_radius")
  183. require_redraw = True
  184. if "border_width" in kwargs:
  185. self._border_width = kwargs.pop("border_width")
  186. self._create_grid()
  187. require_redraw = True
  188. if "fg_color" in kwargs:
  189. self._fg_color = self._check_color_type(kwargs.pop("fg_color"))
  190. require_redraw = True
  191. if "border_color" in kwargs:
  192. self._border_color = self._check_color_type(kwargs.pop("border_color"))
  193. require_redraw = True
  194. if "button_color" in kwargs:
  195. self._button_color = self._check_color_type(kwargs.pop("button_color"))
  196. require_redraw = True
  197. if "button_hover_color" in kwargs:
  198. self._button_hover_color = self._check_color_type(kwargs.pop("button_hover_color"))
  199. require_redraw = True
  200. if "dropdown_fg_color" in kwargs:
  201. self._dropdown_menu.configure(fg_color=kwargs.pop("dropdown_fg_color"))
  202. if "dropdown_hover_color" in kwargs:
  203. self._dropdown_menu.configure(hover_color=kwargs.pop("dropdown_hover_color"))
  204. if "dropdown_text_color" in kwargs:
  205. self._dropdown_menu.configure(text_color=kwargs.pop("dropdown_text_color"))
  206. if "text_color" in kwargs:
  207. self._text_color = self._check_color_type(kwargs.pop("text_color"))
  208. require_redraw = True
  209. if "text_color_disabled" in kwargs:
  210. self._text_color_disabled = self._check_color_type(kwargs.pop("text_color_disabled"))
  211. require_redraw = True
  212. if "font" in kwargs:
  213. if isinstance(self._font, CTkFont):
  214. self._font.remove_size_configure_callback(self._update_font)
  215. self._font = self._check_font_type(kwargs.pop("font"))
  216. if isinstance(self._font, CTkFont):
  217. self._font.add_size_configure_callback(self._update_font)
  218. self._update_font()
  219. if "dropdown_font" in kwargs:
  220. self._dropdown_menu.configure(font=kwargs.pop("dropdown_font"))
  221. if "values" in kwargs:
  222. self._values = kwargs.pop("values")
  223. self._dropdown_menu.configure(values=self._values)
  224. if "state" in kwargs:
  225. self._state = kwargs.pop("state")
  226. self._entry.configure(state=self._state)
  227. require_redraw = True
  228. if "hover" in kwargs:
  229. self._hover = kwargs.pop("hover")
  230. if "variable" in kwargs:
  231. self._variable = kwargs.pop("variable")
  232. self._entry.configure(textvariable=self._variable)
  233. if "command" in kwargs:
  234. self._command = kwargs.pop("command")
  235. if "justify" in kwargs:
  236. self._entry.configure(justify=kwargs.pop("justify"))
  237. super().configure(require_redraw=require_redraw, **kwargs)
  238. def cget(self, attribute_name: str) -> any:
  239. if attribute_name == "corner_radius":
  240. return self._corner_radius
  241. elif attribute_name == "border_width":
  242. return self._border_width
  243. elif attribute_name == "fg_color":
  244. return self._fg_color
  245. elif attribute_name == "border_color":
  246. return self._border_color
  247. elif attribute_name == "button_color":
  248. return self._button_color
  249. elif attribute_name == "button_hover_color":
  250. return self._button_hover_color
  251. elif attribute_name == "dropdown_fg_color":
  252. return self._dropdown_menu.cget("fg_color")
  253. elif attribute_name == "dropdown_hover_color":
  254. return self._dropdown_menu.cget("hover_color")
  255. elif attribute_name == "dropdown_text_color":
  256. return self._dropdown_menu.cget("text_color")
  257. elif attribute_name == "text_color":
  258. return self._text_color
  259. elif attribute_name == "text_color_disabled":
  260. return self._text_color_disabled
  261. elif attribute_name == "font":
  262. return self._font
  263. elif attribute_name == "dropdown_font":
  264. return self._dropdown_menu.cget("font")
  265. elif attribute_name == "values":
  266. return copy.copy(self._values)
  267. elif attribute_name == "state":
  268. return self._state
  269. elif attribute_name == "hover":
  270. return self._hover
  271. elif attribute_name == "variable":
  272. return self._variable
  273. elif attribute_name == "command":
  274. return self._command
  275. elif attribute_name == "justify":
  276. return self._entry.cget("justify")
  277. else:
  278. return super().cget(attribute_name)
  279. def _on_enter(self, event=0):
  280. if self._hover is True and self._state == tkinter.NORMAL and len(self._values) > 0:
  281. if sys.platform == "darwin" and len(self._values) > 0 and self._cursor_manipulation_enabled:
  282. self._canvas.configure(cursor="pointinghand")
  283. elif sys.platform.startswith("win") and len(self._values) > 0 and self._cursor_manipulation_enabled:
  284. self._canvas.configure(cursor="hand2")
  285. # set color of inner button parts to hover color
  286. self._canvas.itemconfig("inner_parts_right",
  287. outline=self._apply_appearance_mode(self._button_hover_color),
  288. fill=self._apply_appearance_mode(self._button_hover_color))
  289. self._canvas.itemconfig("border_parts_right",
  290. outline=self._apply_appearance_mode(self._button_hover_color),
  291. fill=self._apply_appearance_mode(self._button_hover_color))
  292. def _on_leave(self, event=0):
  293. if sys.platform == "darwin" and len(self._values) > 0 and self._cursor_manipulation_enabled:
  294. self._canvas.configure(cursor="arrow")
  295. elif sys.platform.startswith("win") and len(self._values) > 0 and self._cursor_manipulation_enabled:
  296. self._canvas.configure(cursor="arrow")
  297. # set color of inner button parts
  298. self._canvas.itemconfig("inner_parts_right",
  299. outline=self._apply_appearance_mode(self._button_color),
  300. fill=self._apply_appearance_mode(self._button_color))
  301. self._canvas.itemconfig("border_parts_right",
  302. outline=self._apply_appearance_mode(self._button_color),
  303. fill=self._apply_appearance_mode(self._button_color))
  304. def _dropdown_callback(self, value: str):
  305. if self._state == "readonly":
  306. self._entry.configure(state="normal")
  307. self._entry.delete(0, tkinter.END)
  308. self._entry.insert(0, value)
  309. self._entry.configure(state="readonly")
  310. else:
  311. self._entry.delete(0, tkinter.END)
  312. self._entry.insert(0, value)
  313. if self._command is not None:
  314. self._command(value)
  315. def set(self, value: str):
  316. if self._state == "readonly":
  317. self._entry.configure(state="normal")
  318. self._entry.delete(0, tkinter.END)
  319. self._entry.insert(0, value)
  320. self._entry.configure(state="readonly")
  321. else:
  322. self._entry.delete(0, tkinter.END)
  323. self._entry.insert(0, value)
  324. def get(self) -> str:
  325. return self._entry.get()
  326. def _clicked(self, event=None):
  327. if self._state is not tkinter.DISABLED and len(self._values) > 0:
  328. self._open_dropdown_menu()
  329. def bind(self, sequence=None, command=None, add=True):
  330. """ called on the tkinter.Entry """
  331. if not (add == "+" or add is True):
  332. raise ValueError("'add' argument can only be '+' or True to preserve internal callbacks")
  333. self._entry.bind(sequence, command, add=True)
  334. def unbind(self, sequence=None, funcid=None):
  335. """ called on the tkinter.Entry """
  336. if funcid is not None:
  337. raise ValueError("'funcid' argument can only be None, because there is a bug in" +
  338. " tkinter and its not clear whether the internal callbacks will be unbinded or not")
  339. self._entry.unbind(sequence, None) # unbind all callbacks for sequence
  340. self._create_bindings(sequence=sequence) # restore internal callbacks for sequence
  341. def focus(self):
  342. return self._entry.focus()
  343. def focus_set(self):
  344. return self._entry.focus_set()
  345. def focus_force(self):
  346. return self._entry.focus_force()