ctk_switch.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. import tkinter
  2. import sys
  3. from typing import Union, Tuple, Callable, Optional, Any
  4. from .core_rendering import CTkCanvas
  5. from .theme import ThemeManager
  6. from .core_rendering import DrawEngine
  7. from .core_widget_classes import CTkBaseClass
  8. from .font import CTkFont
  9. class CTkSwitch(CTkBaseClass):
  10. """
  11. Switch with rounded corners, border, label, command, variable support.
  12. For detailed information check out the documentation.
  13. """
  14. def __init__(self,
  15. master: Any,
  16. width: int = 100,
  17. height: int = 24,
  18. switch_width: int = 36,
  19. switch_height: int = 18,
  20. corner_radius: Optional[int] = None,
  21. border_width: Optional[int] = None,
  22. button_length: Optional[int] = None,
  23. bg_color: Union[str, Tuple[str, str]] = "transparent",
  24. fg_color: Optional[Union[str, Tuple[str, str]]] = None,
  25. border_color: Union[str, Tuple[str, str]] = "transparent",
  26. progress_color: Optional[Union[str, Tuple[str, str]]] = None,
  27. button_color: Optional[Union[str, Tuple[str, str]]] = None,
  28. button_hover_color: Optional[Union[str, Tuple[str, str]]] = None,
  29. text_color: Optional[Union[str, Tuple[str, str]]] = None,
  30. text_color_disabled: Optional[Union[str, Tuple[str, str]]] = None,
  31. text: str = "CTkSwitch",
  32. font: Optional[Union[tuple, CTkFont]] = None,
  33. textvariable: Union[tkinter.Variable, None] = None,
  34. onvalue: Union[int, str] = 1,
  35. offvalue: Union[int, str] = 0,
  36. variable: Union[tkinter.Variable, None] = None,
  37. hover: bool = True,
  38. command: Union[Callable, Any] = None,
  39. state: str = tkinter.NORMAL,
  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. # dimensions
  44. self._switch_width = switch_width
  45. self._switch_height = switch_height
  46. # color
  47. self._border_color = self._check_color_type(border_color, transparency=True)
  48. self._fg_color = ThemeManager.theme["CTkSwitch"]["fg_color"] if fg_color is None else self._check_color_type(fg_color)
  49. self._progress_color = ThemeManager.theme["CTkSwitch"]["progress_color"] if progress_color is None else self._check_color_type(progress_color, transparency=True)
  50. self._button_color = ThemeManager.theme["CTkSwitch"]["button_color"] if button_color is None else self._check_color_type(button_color)
  51. self._button_hover_color = ThemeManager.theme["CTkSwitch"]["button_hover_color"] if button_hover_color is None else self._check_color_type(button_hover_color)
  52. self._text_color = ThemeManager.theme["CTkSwitch"]["text_color"] if text_color is None else self._check_color_type(text_color)
  53. self._text_color_disabled = ThemeManager.theme["CTkSwitch"]["text_color_disabled"] if text_color_disabled is None else self._check_color_type(text_color_disabled)
  54. # text
  55. self._text = text
  56. self._text_label = None
  57. # font
  58. self._font = CTkFont() if font is None else self._check_font_type(font)
  59. if isinstance(self._font, CTkFont):
  60. self._font.add_size_configure_callback(self._update_font)
  61. # shape
  62. self._corner_radius = ThemeManager.theme["CTkSwitch"]["corner_radius"] if corner_radius is None else corner_radius
  63. self._border_width = ThemeManager.theme["CTkSwitch"]["border_width"] if border_width is None else border_width
  64. self._button_length = ThemeManager.theme["CTkSwitch"]["button_length"] if button_length is None else button_length
  65. self._hover_state: bool = False
  66. self._check_state: bool = False # True if switch is activated
  67. self._hover = hover
  68. self._state = state
  69. self._onvalue = onvalue
  70. self._offvalue = offvalue
  71. # callback and control variables
  72. self._command = command
  73. self._variable = variable
  74. self._variable_callback_blocked = False
  75. self._variable_callback_name = None
  76. self._textvariable = textvariable
  77. # configure grid system (3x1)
  78. self.grid_columnconfigure(0, weight=0)
  79. self.grid_columnconfigure(1, weight=0, minsize=self._apply_widget_scaling(6))
  80. self.grid_columnconfigure(2, weight=1)
  81. self.grid_rowconfigure(0, weight=1)
  82. self._bg_canvas = CTkCanvas(master=self,
  83. highlightthickness=0,
  84. width=self._apply_widget_scaling(self._current_width),
  85. height=self._apply_widget_scaling(self._current_height))
  86. self._bg_canvas.grid(row=0, column=0, columnspan=3, sticky="nswe")
  87. self._canvas = CTkCanvas(master=self,
  88. highlightthickness=0,
  89. width=self._apply_widget_scaling(self._switch_width),
  90. height=self._apply_widget_scaling(self._switch_height))
  91. self._canvas.grid(row=0, column=0, sticky="")
  92. self._draw_engine = DrawEngine(self._canvas)
  93. self._text_label = tkinter.Label(master=self,
  94. bd=0,
  95. padx=0,
  96. pady=0,
  97. text=self._text,
  98. justify=tkinter.LEFT,
  99. font=self._apply_font_scaling(self._font),
  100. textvariable=self._textvariable)
  101. self._text_label.grid(row=0, column=2, sticky="w")
  102. self._text_label["anchor"] = "w"
  103. if self._variable is not None and self._variable != "":
  104. self._variable_callback_name = self._variable.trace_add("write", self._variable_callback)
  105. self._check_state = True if self._variable.get() == self._onvalue else False
  106. self._create_bindings()
  107. self._set_cursor()
  108. self._draw() # initial draw
  109. def _create_bindings(self, sequence: Optional[str] = None):
  110. """ set necessary bindings for functionality of widget, will overwrite other bindings """
  111. if sequence is None or sequence == "<Enter>":
  112. self._canvas.bind("<Enter>", self._on_enter)
  113. self._text_label.bind("<Enter>", self._on_enter)
  114. if sequence is None or sequence == "<Leave>":
  115. self._canvas.bind("<Leave>", self._on_leave)
  116. self._text_label.bind("<Leave>", self._on_leave)
  117. if sequence is None or sequence == "<Button-1>":
  118. self._canvas.bind("<Button-1>", self.toggle)
  119. self._text_label.bind("<Button-1>", self.toggle)
  120. def _set_scaling(self, *args, **kwargs):
  121. super()._set_scaling(*args, **kwargs)
  122. self.grid_columnconfigure(1, weight=0, minsize=self._apply_widget_scaling(6))
  123. self._text_label.configure(font=self._apply_font_scaling(self._font))
  124. self._bg_canvas.configure(width=self._apply_widget_scaling(self._desired_width),
  125. height=self._apply_widget_scaling(self._desired_height))
  126. self._canvas.configure(width=self._apply_widget_scaling(self._switch_width),
  127. height=self._apply_widget_scaling(self._switch_height))
  128. self._draw(no_color_updates=True)
  129. def _set_dimensions(self, width: int = None, height: int = None):
  130. super()._set_dimensions(width, height)
  131. self._bg_canvas.configure(width=self._apply_widget_scaling(self._desired_width),
  132. height=self._apply_widget_scaling(self._desired_height))
  133. def _update_font(self):
  134. """ pass font to tkinter widgets with applied font scaling and update grid with workaround """
  135. self._text_label.configure(font=self._apply_font_scaling(self._font))
  136. # Workaround to force grid to be resized when text changes size.
  137. # Otherwise grid will lag and only resizes if other mouse action occurs.
  138. self._bg_canvas.grid_forget()
  139. self._bg_canvas.grid(row=0, column=0, columnspan=3, sticky="nswe")
  140. def destroy(self):
  141. # remove variable_callback from variable callbacks if variable exists
  142. if self._variable is not None:
  143. self._variable.trace_remove("write", self._variable_callback_name)
  144. if isinstance(self._font, CTkFont):
  145. self._font.remove_size_configure_callback(self._update_font)
  146. super().destroy()
  147. def _set_cursor(self):
  148. if self._cursor_manipulation_enabled:
  149. if self._state == tkinter.DISABLED:
  150. if sys.platform == "darwin":
  151. self._canvas.configure(cursor="arrow")
  152. if self._text_label is not None:
  153. self._text_label.configure(cursor="arrow")
  154. elif sys.platform.startswith("win"):
  155. self._canvas.configure(cursor="arrow")
  156. if self._text_label is not None:
  157. self._text_label.configure(cursor="arrow")
  158. elif self._state == tkinter.NORMAL:
  159. if sys.platform == "darwin":
  160. self._canvas.configure(cursor="pointinghand")
  161. if self._text_label is not None:
  162. self._text_label.configure(cursor="pointinghand")
  163. elif sys.platform.startswith("win"):
  164. self._canvas.configure(cursor="hand2")
  165. if self._text_label is not None:
  166. self._text_label.configure(cursor="hand2")
  167. def _draw(self, no_color_updates=False):
  168. super()._draw(no_color_updates)
  169. if self._check_state is True:
  170. requires_recoloring = self._draw_engine.draw_rounded_slider_with_border_and_button(self._apply_widget_scaling(self._switch_width),
  171. self._apply_widget_scaling(self._switch_height),
  172. self._apply_widget_scaling(self._corner_radius),
  173. self._apply_widget_scaling(self._border_width),
  174. self._apply_widget_scaling(self._button_length),
  175. self._apply_widget_scaling(self._corner_radius),
  176. 1, "w")
  177. else:
  178. requires_recoloring = self._draw_engine.draw_rounded_slider_with_border_and_button(self._apply_widget_scaling(self._switch_width),
  179. self._apply_widget_scaling(self._switch_height),
  180. self._apply_widget_scaling(self._corner_radius),
  181. self._apply_widget_scaling(self._border_width),
  182. self._apply_widget_scaling(self._button_length),
  183. self._apply_widget_scaling(self._corner_radius),
  184. 0, "w")
  185. if no_color_updates is False or requires_recoloring:
  186. self._bg_canvas.configure(bg=self._apply_appearance_mode(self._bg_color))
  187. self._canvas.configure(bg=self._apply_appearance_mode(self._bg_color))
  188. if self._border_color == "transparent":
  189. self._canvas.itemconfig("border_parts",
  190. fill=self._apply_appearance_mode(self._bg_color),
  191. outline=self._apply_appearance_mode(self._bg_color))
  192. else:
  193. self._canvas.itemconfig("border_parts",
  194. fill=self._apply_appearance_mode(self._border_color),
  195. outline=self._apply_appearance_mode(self._border_color))
  196. self._canvas.itemconfig("inner_parts",
  197. fill=self._apply_appearance_mode(self._fg_color),
  198. outline=self._apply_appearance_mode(self._fg_color))
  199. if self._progress_color == "transparent":
  200. self._canvas.itemconfig("progress_parts",
  201. fill=self._apply_appearance_mode(self._fg_color),
  202. outline=self._apply_appearance_mode(self._fg_color))
  203. else:
  204. self._canvas.itemconfig("progress_parts",
  205. fill=self._apply_appearance_mode(self._progress_color),
  206. outline=self._apply_appearance_mode(self._progress_color))
  207. self._canvas.itemconfig("slider_parts",
  208. fill=self._apply_appearance_mode(self._button_color),
  209. outline=self._apply_appearance_mode(self._button_color))
  210. if self._state == tkinter.DISABLED:
  211. self._text_label.configure(fg=(self._apply_appearance_mode(self._text_color_disabled)))
  212. else:
  213. self._text_label.configure(fg=self._apply_appearance_mode(self._text_color))
  214. self._text_label.configure(bg=self._apply_appearance_mode(self._bg_color))
  215. def configure(self, require_redraw=False, **kwargs):
  216. if "corner_radius" in kwargs:
  217. self._corner_radius = kwargs.pop("corner_radius")
  218. require_redraw = True
  219. if "border_width" in kwargs:
  220. self._border_width = kwargs.pop("border_width")
  221. require_redraw = True
  222. if "button_length" in kwargs:
  223. self._button_length = kwargs.pop("button_length")
  224. require_redraw = True
  225. if "switch_width" in kwargs:
  226. self._switch_width = kwargs.pop("switch_width")
  227. self._canvas.configure(width=self._apply_widget_scaling(self._switch_width))
  228. require_redraw = True
  229. if "switch_height" in kwargs:
  230. self._switch_height = kwargs.pop("switch_height")
  231. self._canvas.configure(height=self._apply_widget_scaling(self._switch_height))
  232. require_redraw = True
  233. if "text" in kwargs:
  234. self._text = kwargs.pop("text")
  235. self._text_label.configure(text=self._text)
  236. if "font" in kwargs:
  237. if isinstance(self._font, CTkFont):
  238. self._font.remove_size_configure_callback(self._update_font)
  239. self._font = self._check_font_type(kwargs.pop("font"))
  240. if isinstance(self._font, CTkFont):
  241. self._font.add_size_configure_callback(self._update_font)
  242. self._update_font()
  243. if "state" in kwargs:
  244. self._state = kwargs.pop("state")
  245. self._set_cursor()
  246. require_redraw = True
  247. if "fg_color" in kwargs:
  248. self._fg_color = self._check_color_type(kwargs.pop("fg_color"))
  249. require_redraw = True
  250. if "border_color" in kwargs:
  251. self._border_color = self._check_color_type(kwargs.pop("border_color"), transparency=True)
  252. require_redraw = True
  253. if "progress_color" in kwargs:
  254. self._progress_color = self._check_color_type(kwargs.pop("progress_color"), transparency=True)
  255. require_redraw = True
  256. if "button_color" in kwargs:
  257. self._button_color = self._check_color_type(kwargs.pop("button_color"))
  258. require_redraw = True
  259. if "button_hover_color" in kwargs:
  260. self._button_hover_color = self._check_color_type(kwargs.pop("button_hover_color"))
  261. require_redraw = True
  262. if "text_color" in kwargs:
  263. self._text_color = self._check_color_type(kwargs.pop("text_color"))
  264. require_redraw = True
  265. if "text_color_disabled" in kwargs:
  266. self._text_color_disabled = self._check_color_type(kwargs.pop("text_color_disabled"))
  267. require_redraw = True
  268. if "hover" in kwargs:
  269. self._hover = kwargs.pop("hover")
  270. if "command" in kwargs:
  271. self._command = kwargs.pop("command")
  272. if "textvariable" in kwargs:
  273. self._textvariable = kwargs.pop("textvariable")
  274. self._text_label.configure(textvariable=self._textvariable)
  275. if "variable" in kwargs:
  276. if self._variable is not None and self._variable != "":
  277. self._variable.trace_remove("write", self._variable_callback_name)
  278. self._variable = kwargs.pop("variable")
  279. if self._variable is not None and self._variable != "":
  280. self._variable_callback_name = self._variable.trace_add("write", self._variable_callback)
  281. self._check_state = True if self._variable.get() == self._onvalue else False
  282. require_redraw = True
  283. super().configure(require_redraw=require_redraw, **kwargs)
  284. def cget(self, attribute_name: str) -> any:
  285. if attribute_name == "corner_radius":
  286. return self._corner_radius
  287. elif attribute_name == "border_width":
  288. return self._border_width
  289. elif attribute_name == "button_length":
  290. return self._button_length
  291. elif attribute_name == "switch_width":
  292. return self._switch_width
  293. elif attribute_name == "switch_height":
  294. return self._switch_height
  295. elif attribute_name == "fg_color":
  296. return self._fg_color
  297. elif attribute_name == "border_color":
  298. return self._border_color
  299. elif attribute_name == "progress_color":
  300. return self._progress_color
  301. elif attribute_name == "button_color":
  302. return self._button_color
  303. elif attribute_name == "button_hover_color":
  304. return self._button_hover_color
  305. elif attribute_name == "text_color":
  306. return self._text_color
  307. elif attribute_name == "text_color_disabled":
  308. return self._text_color_disabled
  309. elif attribute_name == "text":
  310. return self._text
  311. elif attribute_name == "font":
  312. return self._font
  313. elif attribute_name == "textvariable":
  314. return self._textvariable
  315. elif attribute_name == "onvalue":
  316. return self._onvalue
  317. elif attribute_name == "offvalue":
  318. return self._offvalue
  319. elif attribute_name == "variable":
  320. return self._variable
  321. elif attribute_name == "hover":
  322. return self._hover
  323. elif attribute_name == "command":
  324. return self._command
  325. elif attribute_name == "state":
  326. return self._state
  327. else:
  328. return super().cget(attribute_name)
  329. def toggle(self, event=None):
  330. if self._state is not tkinter.DISABLED:
  331. if self._check_state is True:
  332. self._check_state = False
  333. else:
  334. self._check_state = True
  335. self._draw(no_color_updates=True)
  336. if self._variable is not None:
  337. self._variable_callback_blocked = True
  338. self._variable.set(self._onvalue if self._check_state is True else self._offvalue)
  339. self._variable_callback_blocked = False
  340. if self._command is not None:
  341. self._command()
  342. def select(self, from_variable_callback=False):
  343. if self._state is not tkinter.DISABLED or from_variable_callback:
  344. self._check_state = True
  345. self._draw(no_color_updates=True)
  346. if self._variable is not None and not from_variable_callback:
  347. self._variable_callback_blocked = True
  348. self._variable.set(self._onvalue)
  349. self._variable_callback_blocked = False
  350. def deselect(self, from_variable_callback=False):
  351. if self._state is not tkinter.DISABLED or from_variable_callback:
  352. self._check_state = False
  353. self._draw(no_color_updates=True)
  354. if self._variable is not None and not from_variable_callback:
  355. self._variable_callback_blocked = True
  356. self._variable.set(self._offvalue)
  357. self._variable_callback_blocked = False
  358. def get(self) -> Union[int, str]:
  359. return self._onvalue if self._check_state is True else self._offvalue
  360. def _on_enter(self, event=0):
  361. if self._hover is True and self._state == "normal":
  362. self._hover_state = True
  363. self._canvas.itemconfig("slider_parts",
  364. fill=self._apply_appearance_mode(self._button_hover_color),
  365. outline=self._apply_appearance_mode(self._button_hover_color))
  366. def _on_leave(self, event=0):
  367. self._hover_state = False
  368. self._canvas.itemconfig("slider_parts",
  369. fill=self._apply_appearance_mode(self._button_color),
  370. outline=self._apply_appearance_mode(self._button_color))
  371. def _variable_callback(self, var_name, index, mode):
  372. if not self._variable_callback_blocked:
  373. if self._variable.get() == self._onvalue:
  374. self.select(from_variable_callback=True)
  375. elif self._variable.get() == self._offvalue:
  376. self.deselect(from_variable_callback=True)
  377. def bind(self, sequence: str = None, command: Callable = None, add: Union[str, bool] = True):
  378. """ called on the tkinter.Canvas """
  379. if not (add == "+" or add is True):
  380. raise ValueError("'add' argument can only be '+' or True to preserve internal callbacks")
  381. self._canvas.bind(sequence, command, add=True)
  382. self._text_label.bind(sequence, command, add=True)
  383. def unbind(self, sequence: str = None, funcid: str = None):
  384. """ called on the tkinter.Label and tkinter.Canvas """
  385. if funcid is not None:
  386. raise ValueError("'funcid' argument can only be None, because there is a bug in" +
  387. " tkinter and its not clear whether the internal callbacks will be unbinded or not")
  388. self._canvas.unbind(sequence, None)
  389. self._text_label.unbind(sequence, None)
  390. self._create_bindings(sequence=sequence) # restore internal callbacks for sequence
  391. def focus(self):
  392. return self._text_label.focus()
  393. def focus_set(self):
  394. return self._text_label.focus_set()
  395. def focus_force(self):
  396. return self._text_label.focus_force()