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

tkinter如何实现复选框左对齐并排成一条直线?

Tkinter的grid布局默认会将控件在所在单元格内居中显示,三个复选框的文本长度不同,导致复选框本体的位置随文本整体偏移。

解决方法是在调用grid()方法时添加sticky='w'参数,该参数会让控件对齐到单元格的西侧(左侧),即可保证所有复选框的选择框保持在同一垂直线上。

修改后参考代码:

has_lower_box = tk.Checkbutton(root, text="lower chars", variable=has_lower_value)
has_lower_box.grid(row=0, column=1, sticky='w')
has_upper_box = tk.Checkbutton(root, text="upper chars", variable=has_upper_value)
has_upper_box.grid(row=1, column=1, sticky='w')
# 原代码此处重复定义了has_upper_box变量,会覆盖之前的大写字母复选框对象,已修正变量名
has_special_box = tk.Checkbutton(root, text="special chars", variable=has_special_value)
has_special_box.grid(row=2, column=1, sticky='w')

如果需要调整左侧边距,还可以在grid参数中添加padx=数值自定义左侧空白距离。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 04:06:03