如何将tkinter创建的按钮布局到窗口左侧?
嘿,我来帮你搞定这个按钮对齐的问题~
你遇到的anchor="w"和side="LEFT"看起来没生效的问题,其实是几个小细节没处理好,我给你拆解一下:
问题1:anchor="w"没效果
Button控件默认的宽度是刚好包裹住文本的,这时候不管你设置anchor是左对齐还是右对齐,都看不出来区别——因为文本已经占满了按钮的宽度。要让anchor生效,你得给按钮一个大于文本宽度的空间,比如设置固定宽度,或者让按钮拉伸填充可用空间。
问题2:side="LEFT"看起来没生效
你的按钮其实已经是左排列了,但因为外层的frame用了pack(fill=None, expand=True),这会让frame在窗口里垂直方向拉伸,但水平方向只包裹按钮的宽度,所以整个按钮组会居中显示在窗口里,看起来像是side=LEFT没起作用。
修改后的代码(带注释)
import tkinter as tk def pressed(): print("button pressed!") def create_layout(frame): # 让frame填充整个窗口的宽高,这样按钮的左对齐会直接显示在窗口左侧 frame.pack(fill=tk.BOTH, expand=True) mycolor = '#%02x%02x%02x' % (250, 250, 210) # 给frame设置背景色(而不是root),因为按钮都放在frame里 frame.configure(bg=mycolor) # 给按钮设置固定宽度,让anchor="w"的左对齐效果显现 button1 = tk.Button(frame, text="Button1", fg="black", command=pressed, anchor="w", width=10) button1.pack(side=tk.LEFT, padx=5, pady=10) # 加边距让布局更舒服 button2 = tk.Button(frame, text="Button2", fg="black", command=pressed, anchor="w", width=10) button2.pack(side=tk.LEFT, padx=5, pady=10) root = tk.Tk() root.geometry("250x150") frame = tk.Frame(root) create_layout(frame) root.mainloop()
可选的另一种方式(不设固定宽度)
如果你不想给按钮固定宽度,也可以让按钮拉伸填充水平空间,把按钮的pack代码改成这样:
button1.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5, pady=10) button2.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5, pady=10)
这样两个按钮会平分窗口的水平空间,文本会靠左对齐,anchor="w"的效果也很明显。
内容的提问来源于stack exchange,提问作者harika
相关产品推荐
相关产品推荐

