ctk_optionmenu.py 19 KB

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