ctk_radiobutton.py 20 KB

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