[Python] How to make a CTkTextbox auto-resize vertically to fit its content in CustomTkinter?

Discussão em 'Python' iniciado por Stack, Abril 10, 2025.

  1. Stack

    Stack Membro Participativo

    I'm using CustomTkinter to build a quiz interface. Each question is displayed in a CTkTextbox (lbl), and I want the textbox to automatically adjust its height (Y dimension) depending on the content, so there's no unnecessary blank space or cut-off text. Here's a simplified version of my current code:

    frames = []
    for idx, (question, answers) in enumerate(questions):
    frame = ctk.CTkFrame(frmcau, fg_color="white", corner_radius=10, border_width=2, border_color="#D3D3D3")
    frame.pack(pady=15, padx=15, fill="x")
    frame.grid_columnconfigure(0, weight=1, uniform=1)
    frame.grid_rowconfigure(0, weight=1)

    lbl = ctk.CTkTextbox(frame, wrap="word", font=("Arial", 16),
    fg_color="white", text_color="black", border_width=0)
    lbl.insert("1.0", f"Câu {idx+1}: {question}")
    lbl.configure(state="disabled")
    lbl.grid(row=0, column=0, sticky="nsew", pady=(5, 0), padx=10)

    for ans_idx, ans in enumerate(answers):
    ctk.CTkRadioButton(
    frame,
    text=ans,
    variable=user_answers[idx],
    value=ans_idx,
    font=("Arial", 14),
    text_color="black",
    hover_color="#E0E0E0"
    ).grid(row=ans_idx + 1, column=0, sticky="we", pady=(0, 5), padx=10)

    frames.append(frame)



    What I tried: Manually calculating the number of lines using textwrap → not accurate.

    Tried update_idletasks() then winfo_height() → doesn't help because height only updates after rendering.

    Is there a reliable way to make a CTkTextbox auto-resize its height based on the text it contains (with wrapping) in pixels or lines, inside a dynamic layout,...?

    I'm open to workarounds, including additional libraries if needed — I just want the display to look clean and readable for long questions. Thanks in advance!

    Continue reading...

Compartilhe esta Página