ctk_slider.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  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. class CTkSlider(CTkBaseClass):
  9. """
  10. Slider with rounded corners, border, number of steps, variable support, vertical orientation.
  11. For detailed information check out the documentation.
  12. """
  13. def __init__(self,
  14. master: Any,
  15. width: Optional[int] = None,
  16. height: Optional[int] = None,
  17. corner_radius: Optional[int] = None,
  18. button_corner_radius: Optional[int] = None,
  19. border_width: Optional[int] = None,
  20. button_length: Optional[int] = None,
  21. bg_color: Union[str, Tuple[str, str]] = "transparent",
  22. fg_color: Optional[Union[str, Tuple[str, str]]] = None,
  23. border_color: Union[str, Tuple[str, str]] = "transparent",
  24. progress_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. from_: int = 0,
  28. to: int = 1,
  29. state: str = "normal",
  30. number_of_steps: Union[int, None] = None,
  31. hover: bool = True,
  32. command: Union[Callable[[float], Any], None] = None,
  33. variable: Union[tkinter.Variable, None] = None,
  34. orientation: str = "horizontal",
  35. **kwargs):
  36. # set default dimensions according to orientation
  37. if width is None:
  38. if orientation.lower() == "vertical":
  39. width = 16
  40. else:
  41. width = 200
  42. if height is None:
  43. if orientation.lower() == "vertical":
  44. height = 200
  45. else:
  46. height = 16
  47. # transfer basic functionality (_bg_color, size, __appearance_mode, scaling) to CTkBaseClass
  48. super().__init__(master=master, bg_color=bg_color, width=width, height=height, **kwargs)
  49. # color
  50. self._border_color = self._check_color_type(border_color, transparency=True)
  51. self._fg_color = ThemeManager.theme["CTkSlider"]["fg_color"] if fg_color is None else self._check_color_type(fg_color)
  52. self._progress_color = ThemeManager.theme["CTkSlider"]["progress_color"] if progress_color is None else self._check_color_type(progress_color, transparency=True)
  53. self._button_color = ThemeManager.theme["CTkSlider"]["button_color"] if button_color is None else self._check_color_type(button_color)
  54. self._button_hover_color = ThemeManager.theme["CTkSlider"]["button_hover_color"] if button_hover_color is None else self._check_color_type(button_hover_color)
  55. # shape
  56. self._corner_radius = ThemeManager.theme["CTkSlider"]["corner_radius"] if corner_radius is None else corner_radius
  57. self._button_corner_radius = ThemeManager.theme["CTkSlider"]["button_corner_radius"] if button_corner_radius is None else button_corner_radius
  58. self._border_width = ThemeManager.theme["CTkSlider"]["border_width"] if border_width is None else border_width
  59. self._button_length = ThemeManager.theme["CTkSlider"]["button_length"] if button_length is None else button_length
  60. self._value: float = 0.5 # initial value of slider in percent
  61. self._orientation = orientation
  62. self._hover_state: bool = False
  63. self._hover = hover
  64. self._from_ = from_
  65. self._to = to
  66. self._number_of_steps = number_of_steps
  67. self._output_value = self._from_ + (self._value * (self._to - self._from_))
  68. if self._corner_radius < self._button_corner_radius:
  69. self._corner_radius = self._button_corner_radius
  70. # callback and control variables
  71. self._command = command
  72. self._variable: tkinter.Variable = variable
  73. self._variable_callback_blocked: bool = False
  74. self._variable_callback_name: Union[bool, None] = None
  75. self._state = state
  76. self.grid_rowconfigure(0, weight=1)
  77. self.grid_columnconfigure(0, weight=1)
  78. self._canvas = CTkCanvas(master=self,
  79. highlightthickness=0,
  80. width=self._apply_widget_scaling(self._desired_width),
  81. height=self._apply_widget_scaling(self._desired_height))
  82. self._canvas.grid(column=0, row=0, rowspan=1, columnspan=1, sticky="nswe")
  83. self._draw_engine = DrawEngine(self._canvas)
  84. self._create_bindings()
  85. self._set_cursor()
  86. self._draw() # initial draw
  87. if self._variable is not None:
  88. self._variable_callback_name = self._variable.trace_add("write", self._variable_callback)
  89. self._variable_callback_blocked = True
  90. self.set(self._variable.get(), from_variable_callback=True)
  91. self._variable_callback_blocked = False
  92. def _create_bindings(self, sequence: Optional[str] = None):
  93. """ set necessary bindings for functionality of widget, will overwrite other bindings """
  94. if sequence is None or sequence == "<Enter>":
  95. self._canvas.bind("<Enter>", self._on_enter)
  96. if sequence is None or sequence == "<Leave>":
  97. self._canvas.bind("<Leave>", self._on_leave)
  98. if sequence is None or sequence == "<Button-1>":
  99. self._canvas.bind("<Button-1>", self._clicked)
  100. if sequence is None or sequence == "<B1-Motion>":
  101. self._canvas.bind("<B1-Motion>", self._clicked)
  102. def _set_scaling(self, *args, **kwargs):
  103. super()._set_scaling(*args, **kwargs)
  104. self._canvas.configure(width=self._apply_widget_scaling(self._desired_width),
  105. height=self._apply_widget_scaling(self._desired_height))
  106. self._draw(no_color_updates=True)
  107. def _set_dimensions(self, width=None, height=None):
  108. super()._set_dimensions(width, height)
  109. self._canvas.configure(width=self._apply_widget_scaling(self._desired_width),
  110. height=self._apply_widget_scaling(self._desired_height))
  111. self._draw()
  112. def destroy(self):
  113. # remove variable_callback from variable callbacks if variable exists
  114. if self._variable is not None:
  115. self._variable.trace_remove("write", self._variable_callback_name)
  116. super().destroy()
  117. def _set_cursor(self):
  118. if self._state == "normal" and self._cursor_manipulation_enabled:
  119. if sys.platform == "darwin":
  120. self.configure(cursor="pointinghand")
  121. elif sys.platform.startswith("win"):
  122. self.configure(cursor="hand2")
  123. elif self._state == "disabled" and self._cursor_manipulation_enabled:
  124. if sys.platform == "darwin":
  125. self.configure(cursor="arrow")
  126. elif sys.platform.startswith("win"):
  127. self.configure(cursor="arrow")
  128. def _draw(self, no_color_updates=False):
  129. super()._draw(no_color_updates)
  130. if self._orientation.lower() == "horizontal":
  131. orientation = "w"
  132. elif self._orientation.lower() == "vertical":
  133. orientation = "s"
  134. else:
  135. orientation = "w"
  136. requires_recoloring = self._draw_engine.draw_rounded_slider_with_border_and_button(self._apply_widget_scaling(self._current_width),
  137. self._apply_widget_scaling(self._current_height),
  138. self._apply_widget_scaling(self._corner_radius),
  139. self._apply_widget_scaling(self._border_width),
  140. self._apply_widget_scaling(self._button_length),
  141. self._apply_widget_scaling(self._button_corner_radius),
  142. self._value, orientation)
  143. if no_color_updates is False or requires_recoloring:
  144. self._canvas.configure(bg=self._apply_appearance_mode(self._bg_color))
  145. if self._border_color == "transparent":
  146. self._canvas.itemconfig("border_parts", fill=self._apply_appearance_mode(self._bg_color),
  147. outline=self._apply_appearance_mode(self._bg_color))
  148. else:
  149. self._canvas.itemconfig("border_parts", fill=self._apply_appearance_mode(self._border_color),
  150. outline=self._apply_appearance_mode(self._border_color))
  151. self._canvas.itemconfig("inner_parts", fill=self._apply_appearance_mode(self._fg_color),
  152. outline=self._apply_appearance_mode(self._fg_color))
  153. if self._progress_color == "transparent":
  154. self._canvas.itemconfig("progress_parts", fill=self._apply_appearance_mode(self._fg_color),
  155. outline=self._apply_appearance_mode(self._fg_color))
  156. else:
  157. self._canvas.itemconfig("progress_parts", fill=self._apply_appearance_mode(self._progress_color),
  158. outline=self._apply_appearance_mode(self._progress_color))
  159. if self._hover_state is True:
  160. self._canvas.itemconfig("slider_parts",
  161. fill=self._apply_appearance_mode(self._button_hover_color),
  162. outline=self._apply_appearance_mode(self._button_hover_color))
  163. else:
  164. self._canvas.itemconfig("slider_parts",
  165. fill=self._apply_appearance_mode(self._button_color),
  166. outline=self._apply_appearance_mode(self._button_color))
  167. def configure(self, require_redraw=False, **kwargs):
  168. if "corner_radius" in kwargs:
  169. self._corner_radius = kwargs.pop("corner_radius")
  170. require_redraw = True
  171. if "button_corner_radius" in kwargs:
  172. self._button_corner_radius = kwargs.pop("button_corner_radius")
  173. require_redraw = True
  174. if "border_width" in kwargs:
  175. self._border_width = kwargs.pop("border_width")
  176. require_redraw = True
  177. if "button_length" in kwargs:
  178. self._button_length = kwargs.pop("button_length")
  179. require_redraw = True
  180. if "fg_color" in kwargs:
  181. self._fg_color = self._check_color_type(kwargs.pop("fg_color"))
  182. require_redraw = True
  183. if "border_color" in kwargs:
  184. self._border_color = self._check_color_type(kwargs.pop("border_color"), transparency=True)
  185. require_redraw = True
  186. if "progress_color" in kwargs:
  187. self._progress_color = self._check_color_type(kwargs.pop("progress_color"), transparency=True)
  188. require_redraw = True
  189. if "button_color" in kwargs:
  190. self._button_color = self._check_color_type(kwargs.pop("button_color"))
  191. require_redraw = True
  192. if "button_hover_color" in kwargs:
  193. self._button_hover_color = self._check_color_type(kwargs.pop("button_hover_color"))
  194. require_redraw = True
  195. if "from_" in kwargs:
  196. self._from_ = kwargs.pop("from_")
  197. if "to" in kwargs:
  198. self._to = kwargs.pop("to")
  199. if "state" in kwargs:
  200. self._state = kwargs.pop("state")
  201. self._set_cursor()
  202. require_redraw = True
  203. if "number_of_steps" in kwargs:
  204. self._number_of_steps = kwargs.pop("number_of_steps")
  205. if "hover" in kwargs:
  206. self._hover = kwargs.pop("hover")
  207. if "command" in kwargs:
  208. self._command = kwargs.pop("command")
  209. if "variable" in kwargs:
  210. if self._variable is not None:
  211. self._variable.trace_remove("write", self._variable_callback_name)
  212. self._variable = kwargs.pop("variable")
  213. if self._variable is not None and self._variable != "":
  214. self._variable_callback_name = self._variable.trace_add("write", self._variable_callback)
  215. self.set(self._variable.get(), from_variable_callback=True)
  216. else:
  217. self._variable = None
  218. if "orientation" in kwargs:
  219. self._orientation = kwargs.pop("orientation")
  220. require_redraw = True
  221. super().configure(require_redraw=require_redraw, **kwargs)
  222. def cget(self, attribute_name: str) -> any:
  223. if attribute_name == "corner_radius":
  224. return self._corner_radius
  225. elif attribute_name == "button_corner_radius":
  226. return self._button_corner_radius
  227. elif attribute_name == "border_width":
  228. return self._border_width
  229. elif attribute_name == "button_length":
  230. return self._button_length
  231. elif attribute_name == "fg_color":
  232. return self._fg_color
  233. elif attribute_name == "border_color":
  234. return self._border_color
  235. elif attribute_name == "progress_color":
  236. return self._progress_color
  237. elif attribute_name == "button_color":
  238. return self._button_color
  239. elif attribute_name == "button_hover_color":
  240. return self._button_hover_color
  241. elif attribute_name == "from_":
  242. return self._from_
  243. elif attribute_name == "to":
  244. return self._to
  245. elif attribute_name == "state":
  246. return self._state
  247. elif attribute_name == "number_of_steps":
  248. return self._number_of_steps
  249. elif attribute_name == "hover":
  250. return self._hover
  251. elif attribute_name == "command":
  252. return self._command
  253. elif attribute_name == "variable":
  254. return self._variable
  255. elif attribute_name == "orientation":
  256. return self._orientation
  257. else:
  258. return super().cget(attribute_name)
  259. def _clicked(self, event=None):
  260. if self._state == "normal":
  261. if self._orientation.lower() == "horizontal":
  262. self._value = self._reverse_widget_scaling(event.x / self._current_width)
  263. else:
  264. self._value = 1 - self._reverse_widget_scaling(event.y / self._current_height)
  265. if self._value > 1:
  266. self._value = 1
  267. if self._value < 0:
  268. self._value = 0
  269. self._output_value = self._round_to_step_size(self._from_ + (self._value * (self._to - self._from_)))
  270. self._value = (self._output_value - self._from_) / (self._to - self._from_)
  271. self._draw(no_color_updates=False)
  272. if self._variable is not None:
  273. self._variable_callback_blocked = True
  274. self._variable.set(round(self._output_value) if isinstance(self._variable, tkinter.IntVar) else self._output_value)
  275. self._variable_callback_blocked = False
  276. if self._command is not None:
  277. self._command(self._output_value)
  278. def _on_enter(self, event=0):
  279. if self._hover is True and self._state == "normal":
  280. self._hover_state = True
  281. self._canvas.itemconfig("slider_parts",
  282. fill=self._apply_appearance_mode(self._button_hover_color),
  283. outline=self._apply_appearance_mode(self._button_hover_color))
  284. def _on_leave(self, event=0):
  285. self._hover_state = False
  286. self._canvas.itemconfig("slider_parts",
  287. fill=self._apply_appearance_mode(self._button_color),
  288. outline=self._apply_appearance_mode(self._button_color))
  289. def _round_to_step_size(self, value) -> float:
  290. if self._number_of_steps is not None:
  291. step_size = (self._to - self._from_) / self._number_of_steps
  292. value = self._to - (round((self._to - value) / step_size) * step_size)
  293. return value
  294. else:
  295. return value
  296. def get(self) -> float:
  297. return self._output_value
  298. def set(self, output_value, from_variable_callback=False):
  299. if self._from_ < self._to:
  300. if output_value > self._to:
  301. output_value = self._to
  302. elif output_value < self._from_:
  303. output_value = self._from_
  304. else:
  305. if output_value < self._to:
  306. output_value = self._to
  307. elif output_value > self._from_:
  308. output_value = self._from_
  309. self._output_value = self._round_to_step_size(output_value)
  310. self._value = (self._output_value - self._from_) / (self._to - self._from_)
  311. self._draw(no_color_updates=False)
  312. if self._variable is not None and not from_variable_callback:
  313. self._variable_callback_blocked = True
  314. self._variable.set(round(self._output_value) if isinstance(self._variable, tkinter.IntVar) else self._output_value)
  315. self._variable_callback_blocked = False
  316. def _variable_callback(self, var_name, index, mode):
  317. if not self._variable_callback_blocked:
  318. self.set(self._variable.get(), from_variable_callback=True)
  319. def bind(self, sequence: str = None, command: Callable = None, add: Union[str, bool] = True):
  320. """ called on the tkinter.Canvas """
  321. if not (add == "+" or add is True):
  322. raise ValueError("'add' argument can only be '+' or True to preserve internal callbacks")
  323. self._canvas.bind(sequence, command, add=True)
  324. def unbind(self, sequence: str = None, funcid: str = None):
  325. """ called on the tkinter.Label and tkinter.Canvas """
  326. if funcid is not None:
  327. raise ValueError("'funcid' argument can only be None, because there is a bug in" +
  328. " tkinter and its not clear whether the internal callbacks will be unbinded or not")
  329. self._canvas.unbind(sequence, None)
  330. self._create_bindings(sequence=sequence) # restore internal callbacks for sequence
  331. def focus(self):
  332. return self._canvas.focus()
  333. def focus_set(self):
  334. return self._canvas.focus_set()
  335. def focus_force(self):
  336. return self._canvas.focus_force()