Dynamic configuration of CTkLabel wraplength not working on dual monitor setup #2681
-
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 5 replies
-
Use ...
lbl_description.update()
lbl_description.configure(wraplength=lbl_description.winfo_width())
... Alternatively, you can directly access accurate width from ...
lbl_description.configure(wraplength=event.width)
... |
Beta Was this translation helpful? Give feedback.
-
@debicarroll You are right. The from customtkinter import (
CTk,
CTkFont,
AppearanceModeTracker,
ThemeManager
)
from tkinter import Event, Label
class WrappableLabel(Label):
def __init__(self,
master=None,
text: str = "Sample Text",
fg_color: str | tuple[str, str] = None,
text_color: str | tuple[str, str] = None,
font: CTkFont | tuple[str, str, int] = None,
**kwargs):
"""Auto-wrap text in customtkinter. It wraps text in words based on window size."""
self._font = CTkFont() if not font else font
self._text = "Sample Text" if not text else text
self._fg_color = master["bg"] if not fg_color else fg_color
self._text_color = ThemeManager.theme["CTkLabel"]["text_color"] if not text_color else text_color
super().__init__(master, text=text, foreground=self._get_color(self._text_color), font=self._font, bg=self._get_color(self._fg_color), **kwargs)
self.master.bind("<Configure>", self._on_config, "+")
AppearanceModeTracker.add(self._on_apprearance)
def _on_config(self, event: Event):
wrappable = event.width - self._font.measure(".")
self.configure(wraplength=wrappable)
def _get_color(self, color: str | tuple[str, str]) -> str:
if isinstance(color, str):
return color
elif isinstance(color, (tuple, list)):
return color[AppearanceModeTracker.get_mode()]
def _on_apprearance(self, m=None):
self.configure(bg=self._get_color(self.master.cget("bg")))
self.configure(foreground=self._get_color(self._text_color))
if __name__ == "__main__":
app = CTk()
app.geometry("530x300")
app.pack_propagate(False)
lengthy_text = "One (1) Two (2) Three (3) Four (4) Five (5) Six (6) Seven (7) Eight (8) Nine (9) Ten (10)."
lab = WrappableLabel(app, text=lengthy_text, anchor="w")
lab.pack(side="left", padx=10, pady=10)
app.mainloop() Output: If the provided code does not work expectedly, let me know. |
Beta Was this translation helpful? Give feedback.
@debicarroll You are right. The
wrap="word"
parameter is only supported inText
widget, not inLabel
. If you want responsive text area for the application then it is recommended to useText
widget instead ofLabel
in tkinter or customtkinter. Although, I wrote a fully wrap-supportive label class for customtkinter. Here it is: