You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Customtkinter复选框X轴对齐异常及长文本显示问题求助

解决CustomTkinter Todo应用复选框对齐与长文本异常问题

问题根源

  • 使用grid布局时未配置列权重,控件无法自适应滚动框宽度,长文本超出后被截断甚至消失
  • 复选框与输入框未设置对齐属性,导致X轴起始位置不一致

修改后的完整代码

from customtkinter import *
import random

root = CTk()
root.geometry('400x600')
root.title('Todo')
root.resizable(False, False)
set_appearance_mode('light')
set_default_color_theme('blue')

# Main label
main_label = CTkLabel(root, text='Your To Do list', font=CTkFont(size=30, weight='bold'))
main_label.place(x=20, y=20)

# Under label
under_label_choices_list = [
    'This will be your best day',
    'Be productive',
    'Willpower',
]
under_label_choices = StringVar()
under_label_choices.set(random.choice(under_label_choices_list))

under_label = CTkLabel(root, textvariable=under_label_choices, text_color='#6495ED', font=CTkFont(size=15, weight='bold'))
under_label.place(x=20, y=50)

# Scrollableframe
scrollableframe = CTkScrollableFrame(root, width=300, height=400)
scrollableframe.place(x=40, y=100)
# 配置第0列自动填充宽度
scrollableframe.grid_columnconfigure(0, weight=1)

# Add button
def make_checkbox(event):
    global todo_entry
    # 设置换行宽度+左对齐,避免长文本消失
    checkbox = CTkCheckBox(scrollableframe, text=todo_entry.get(), font=CTkFont(size=15), width=0, wraplength=280)
    todo_entry.destroy()
    checkbox.grid(padx=5, pady=5, sticky="w")

def add():
    global todo_entry
    todo_entry = CTkEntry(scrollableframe)
    todo_entry.bind('<Return>', make_checkbox)
    # 让输入框填充整列,和复选框保持宽度基准一致
    todo_entry.grid(padx=5, pady=5, sticky="ew")
    todo_entry.focus()

add_button = CTkButton(root, text='Add', command=add)
add_button.place(x=20, y=540)

root.mainloop()

关键修改说明

  • 滚动框列配置:添加scrollableframe.grid_columnconfigure(0, weight=1),让第0列随滚动框宽度自动扩展,保证控件能利用可用空间
  • 输入框布局:todo_entry.grid(..., sticky="ew"),让输入框横向填充整列,和复选框保持一致的宽度基准
  • 复选框配置:
    • width=0:让复选框根据文本长度自动调整宽度,避免固定宽度截断文本
    • wraplength=280:设置文本换行宽度(适配滚动框300px宽度,减去左右内边距),长文本自动换行不会消失
    • sticky="w":强制复选框左对齐,确保所有复选框X轴起始位置统一

内容的提问来源于stack exchange,提问作者Illes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 10:29:59