ctk_progressbar.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. import tkinter
  2. import math
  3. from typing import Union, Tuple, Optional, Callable, Any
  4. try:
  5. from typing import Literal
  6. except ImportError:
  7. from typing_extensions import Literal
  8. from .core_rendering import CTkCanvas
  9. from .theme import ThemeManager
  10. from .core_rendering import DrawEngine
  11. from .core_widget_classes import CTkBaseClass
  12. class CTkProgressBar(CTkBaseClass):
  13. """
  14. Progressbar with rounded corners, border, variable support,
  15. indeterminate mode, vertical orientation.
  16. For detailed information check out the documentation.
  17. """
  18. def __init__(self,
  19. master: Any,
  20. width: Optional[int] = None,
  21. height: Optional[int] = None,
  22. corner_radius: Optional[int] = None,
  23. border_width: Optional[int] = None,
  24. bg_color: Union[str, Tuple[str, str]] = "transparent",
  25. fg_color: Optional[Union[str, Tuple[str, str]]] = None,
  26. border_color: Optional[Union[str, Tuple[str, str]]] = None,
  27. progress_color: Optional[Union[str, Tuple[str, str]]] = None,
  28. variable: Union[tkinter.Variable, None] = None,
  29. orientation: str = "horizontal",
  30. mode: Literal["determinate", "indeterminate"] = "determinate",
  31. determinate_speed: float = 1,
  32. indeterminate_speed: float = 1,
  33. **kwargs):
  34. # set default dimensions according to orientation
  35. if width is None:
  36. if orientation.lower() == "vertical":
  37. width = 8
  38. else:
  39. width = 200
  40. if height is None:
  41. if orientation.lower() == "vertical":
  42. height = 200
  43. else:
  44. height = 8
  45. # transfer basic functionality (_bg_color, size, __appearance_mode, scaling) to CTkBaseClass
  46. super().__init__(master=master, bg_color=bg_color, width=width, height=height, **kwargs)
  47. # color
  48. self._border_color = ThemeManager.theme["CTkProgressBar"]["border_color"] if border_color is None else self._check_color_type(border_color)
  49. self._fg_color = ThemeManager.theme["CTkProgressBar"]["fg_color"] if fg_color is None else self._check_color_type(fg_color)
  50. self._progress_color = ThemeManager.theme["CTkProgressBar"]["progress_color"] if progress_color is None else self._check_color_type(progress_color)
  51. # control variable
  52. self._variable = variable
  53. self._variable_callback_blocked = False
  54. self._variable_callback_name = None
  55. self._loop_after_id = None
  56. # shape
  57. self._corner_radius = ThemeManager.theme["CTkProgressBar"]["corner_radius"] if corner_radius is None else corner_radius
  58. self._border_width = ThemeManager.theme["CTkProgressBar"]["border_width"] if border_width is None else border_width
  59. self._determinate_value: float = 0.5 # range 0-1
  60. self._determinate_speed = determinate_speed # range 0-1
  61. self._indeterminate_value: float = 0 # range 0-inf
  62. self._indeterminate_width: float = 0.4 # range 0-1
  63. self._indeterminate_speed = indeterminate_speed # range 0-1 to travel in 50ms
  64. self._loop_running: bool = False
  65. self._orientation = orientation
  66. self._mode = mode # "determinate" or "indeterminate"
  67. self.grid_rowconfigure(0, weight=1)
  68. self.grid_columnconfigure(0, weight=1)
  69. self._canvas = CTkCanvas(master=self,
  70. highlightthickness=0,
  71. width=self._apply_widget_scaling(self._desired_width),
  72. height=self._apply_widget_scaling(self._desired_height))
  73. self._canvas.grid(row=0, column=0, rowspan=1, columnspan=1, sticky="nswe")
  74. self._draw_engine = DrawEngine(self._canvas)
  75. self._draw() # initial draw
  76. if self._variable is not None:
  77. self._variable_callback_name = self._variable.trace_add("write", self._variable_callback)
  78. self._variable_callback_blocked = True
  79. self.set(self._variable.get(), from_variable_callback=True)
  80. self._variable_callback_blocked = False
  81. def _set_scaling(self, *args, **kwargs):
  82. super()._set_scaling(*args, **kwargs)
  83. self._canvas.configure(width=self._apply_widget_scaling(self._desired_width),
  84. height=self._apply_widget_scaling(self._desired_height))
  85. self._draw(no_color_updates=True)
  86. def _set_dimensions(self, width=None, height=None):
  87. super()._set_dimensions(width, height)
  88. self._canvas.configure(width=self._apply_widget_scaling(self._desired_width),
  89. height=self._apply_widget_scaling(self._desired_height))
  90. self._draw()
  91. def destroy(self):
  92. if self._variable is not None:
  93. self._variable.trace_remove("write", self._variable_callback_name)
  94. super().destroy()
  95. def _draw(self, no_color_updates=False):
  96. super()._draw(no_color_updates)
  97. if self._orientation.lower() == "horizontal":
  98. orientation = "w"
  99. elif self._orientation.lower() == "vertical":
  100. orientation = "s"
  101. else:
  102. orientation = "w"
  103. if self._mode == "determinate":
  104. requires_recoloring = self._draw_engine.draw_rounded_progress_bar_with_border(self._apply_widget_scaling(self._current_width),
  105. self._apply_widget_scaling(self._current_height),
  106. self._apply_widget_scaling(self._corner_radius),
  107. self._apply_widget_scaling(self._border_width),
  108. 0,
  109. self._determinate_value,
  110. orientation)
  111. else: # indeterminate mode
  112. progress_value = (math.sin(self._indeterminate_value * math.pi / 40) + 1) / 2
  113. progress_value_1 = min(1.0, progress_value + (self._indeterminate_width / 2))
  114. progress_value_2 = max(0.0, progress_value - (self._indeterminate_width / 2))
  115. requires_recoloring = self._draw_engine.draw_rounded_progress_bar_with_border(self._apply_widget_scaling(self._current_width),
  116. self._apply_widget_scaling(self._current_height),
  117. self._apply_widget_scaling(self._corner_radius),
  118. self._apply_widget_scaling(self._border_width),
  119. progress_value_1,
  120. progress_value_2,
  121. orientation)
  122. if no_color_updates is False or requires_recoloring:
  123. self._canvas.configure(bg=self._apply_appearance_mode(self._bg_color))
  124. self._canvas.itemconfig("border_parts",
  125. fill=self._apply_appearance_mode(self._border_color),
  126. outline=self._apply_appearance_mode(self._border_color))
  127. self._canvas.itemconfig("inner_parts",
  128. fill=self._apply_appearance_mode(self._fg_color),
  129. outline=self._apply_appearance_mode(self._fg_color))
  130. self._canvas.itemconfig("progress_parts",
  131. fill=self._apply_appearance_mode(self._progress_color),
  132. outline=self._apply_appearance_mode(self._progress_color))
  133. def configure(self, require_redraw=False, **kwargs):
  134. if "corner_radius" in kwargs:
  135. self._corner_radius = kwargs.pop("corner_radius")
  136. require_redraw = True
  137. if "border_width" in kwargs:
  138. self._border_width = kwargs.pop("border_width")
  139. require_redraw = True
  140. if "fg_color" in kwargs:
  141. self._fg_color = self._check_color_type(kwargs.pop("fg_color"))
  142. require_redraw = True
  143. if "border_color" in kwargs:
  144. self._border_color = self._check_color_type(kwargs.pop("border_color"))
  145. require_redraw = True
  146. if "progress_color" in kwargs:
  147. self._progress_color = self._check_color_type(kwargs.pop("progress_color"))
  148. require_redraw = True
  149. if "variable" in kwargs:
  150. if self._variable is not None:
  151. self._variable.trace_remove("write", self._variable_callback_name)
  152. self._variable = kwargs.pop("variable")
  153. if self._variable is not None and self._variable != "":
  154. self._variable_callback_name = self._variable.trace_add("write", self._variable_callback)
  155. self.set(self._variable.get(), from_variable_callback=True)
  156. else:
  157. self._variable = None
  158. if "mode" in kwargs:
  159. self._mode = kwargs.pop("mode")
  160. require_redraw = True
  161. if "determinate_speed" in kwargs:
  162. self._determinate_speed = kwargs.pop("determinate_speed")
  163. if "indeterminate_speed" in kwargs:
  164. self._indeterminate_speed = kwargs.pop("indeterminate_speed")
  165. super().configure(require_redraw=require_redraw, **kwargs)
  166. def cget(self, attribute_name: str) -> any:
  167. if attribute_name == "corner_radius":
  168. return self._corner_radius
  169. elif attribute_name == "border_width":
  170. return self._border_width
  171. elif attribute_name == "fg_color":
  172. return self._fg_color
  173. elif attribute_name == "border_color":
  174. return self._border_color
  175. elif attribute_name == "progress_color":
  176. return self._progress_color
  177. elif attribute_name == "variable":
  178. return self._variable
  179. elif attribute_name == "orientation":
  180. return self._orientation
  181. elif attribute_name == "mode":
  182. return self._mode
  183. elif attribute_name == "determinate_speed":
  184. return self._determinate_speed
  185. elif attribute_name == "indeterminate_speed":
  186. return self._indeterminate_speed
  187. else:
  188. return super().cget(attribute_name)
  189. def _variable_callback(self, var_name, index, mode):
  190. if not self._variable_callback_blocked:
  191. self.set(self._variable.get(), from_variable_callback=True)
  192. def set(self, value, from_variable_callback=False):
  193. """ set determinate value """
  194. self._determinate_value = value
  195. if self._determinate_value > 1:
  196. self._determinate_value = 1
  197. elif self._determinate_value < 0:
  198. self._determinate_value = 0
  199. self._draw(no_color_updates=True)
  200. if self._variable is not None and not from_variable_callback:
  201. self._variable_callback_blocked = True
  202. self._variable.set(round(self._determinate_value) if isinstance(self._variable, tkinter.IntVar) else self._determinate_value)
  203. self._variable_callback_blocked = False
  204. def get(self) -> float:
  205. """ get determinate value """
  206. return self._determinate_value
  207. def start(self):
  208. """ start automatic mode """
  209. if not self._loop_running:
  210. self._loop_running = True
  211. self._internal_loop()
  212. def stop(self):
  213. """ stop automatic mode """
  214. if self._loop_after_id is not None:
  215. self.after_cancel(self._loop_after_id)
  216. self._loop_running = False
  217. def _internal_loop(self):
  218. if self._loop_running:
  219. if self._mode == "determinate":
  220. self._determinate_value += self._determinate_speed / 50
  221. if self._determinate_value > 1:
  222. self._determinate_value -= 1
  223. self._draw()
  224. self._loop_after_id = self.after(20, self._internal_loop)
  225. else:
  226. self._indeterminate_value += self._indeterminate_speed
  227. self._draw()
  228. self._loop_after_id = self.after(20, self._internal_loop)
  229. def step(self):
  230. """ increase progress """
  231. if self._mode == "determinate":
  232. self._determinate_value += self._determinate_speed / 50
  233. if self._determinate_value > 1:
  234. self._determinate_value -= 1
  235. self._draw()
  236. else:
  237. self._indeterminate_value += self._indeterminate_speed
  238. self._draw()
  239. def bind(self, sequence: str = None, command: Callable = None, add: Union[str, bool] = True):
  240. """ called on the tkinter.Canvas """
  241. if not (add == "+" or add is True):
  242. raise ValueError("'add' argument can only be '+' or True to preserve internal callbacks")
  243. self._canvas.bind(sequence, command, add=True)
  244. def unbind(self, sequence: str = None, funcid: str = None):
  245. """ called on the tkinter.Label and tkinter.Canvas """
  246. if funcid is not None:
  247. raise ValueError("'funcid' argument can only be None, because there is a bug in" +
  248. " tkinter and its not clear whether the internal callbacks will be unbinded or not")
  249. self._canvas.unbind(sequence, None)
  250. def focus(self):
  251. return self._canvas.focus()
  252. def focus_set(self):
  253. return self._canvas.focus_set()
  254. def focus_force(self):
  255. return self._canvas.focus_force()