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

如何设置Tkinter按钮统一宽度并实现文本左对齐?

问题描述

请看以下代码:

from tkinter import mainloop, Button
import tkinter as tk

def cmd():
    print('Hello World')

class my_class(tk.Tk):
    def __init__(self):
        super().__init__()
        Button(self, text="Button A", command = cmd ).place(x=10, y=10)
        Button(self, text="Button B has a long name", command = cmd).place(x=10, y=60)
        Button(self, text="Button C has a long name", command = cmd, width = 25 ).place(x=10, y=110)
        Button(self, text="Button D", command = cmd, width = 25 ).place(x=10, y=160) 
           
    
if __name__ == '__main__':
    app = my_class()
    app.geometry = ('400x300')
    app.mainloop()

运行上述代码后,上方两个按钮文本左对齐但宽度不同;下方两个按钮宽度一致但文本居中。需要实现所有按钮宽度统一且文本左对齐。

解决方法

要达成需求,只需给每个按钮添加两个关键参数,同时修正原代码的一处错误:

  1. 给所有按钮设置统一的width值(比如25,可按需调整),确保宽度一致
  2. 添加anchor='w'参数,让按钮内文本左对齐('w'代表west,即左侧方向)
  3. 修正app.geometry的写法:原代码是赋值操作,正确应该是调用方法app.geometry('400x300')

修改后的完整代码如下:

from tkinter import mainloop, Button
import tkinter as tk

def cmd():
    print('Hello World')

class my_class(tk.Tk):
    def __init__(self):
        super().__init__()
        Button(self, text="Button A", command=cmd, width=25, anchor='w').place(x=10, y=10)
        Button(self, text="Button B has a long name", command=cmd, width=25, anchor='w').place(x=10, y=60)
        Button(self, text="Button C has a long name", command=cmd, width=25, anchor='w').place(x=10, y=110)
        Button(self, text="Button D", command=cmd, width=25, anchor='w').place(x=10, y=160) 
           
    
if __name__ == '__main__':
    app = my_class()
    app.geometry('400x300')
    app.mainloop()
补充说明
  • anchor参数可控制文本在按钮内的对齐方向,除了'w'左对齐,还支持'e'右对齐、'center'居中、'n'上对齐等选项
  • width参数的单位是字符宽度,设置统一值后,不管按钮文本长短,都会保持相同的宽度

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 00:32:15