如何设置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()
运行上述代码后,上方两个按钮文本左对齐但宽度不同;下方两个按钮宽度一致但文本居中。需要实现所有按钮宽度统一且文本左对齐。
解决方法
要达成需求,只需给每个按钮添加两个关键参数,同时修正原代码的一处错误:
- 给所有按钮设置统一的
width值(比如25,可按需调整),确保宽度一致 - 添加
anchor='w'参数,让按钮内文本左对齐('w'代表west,即左侧方向) - 修正
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
相关产品推荐
相关产品推荐

