Center align a group of widgets in a frame

前端 未结 1 1564
轮回少年
轮回少年 2021-01-20 04:52

If there\'s a single widget in a frame\'s row, I can align it to any side with sticky=, or center align by omitting sticky.

However, when t

相关标签:
1条回答
  • 2021-01-20 05:44

    The simplest solution for horizontally centering a group of widgets when using grid is to create an empty column to to the left and right of all of the visible items, and then give those columns a weight so that all extra space is allocated to the empty columns.

    Example

    import Tkinter as tk
    
    root = tk.Tk()
    root.geometry("400x200")
    
    label = tk.Label(root, text="Hello, world")
    buttons = tk.Frame(root)
    label.pack(side="top", fill="both", expand=True)
    buttons.pack(side="bottom", fill="x")
    
    b1 = tk.Button(buttons, text="one")
    b2 = tk.Button(buttons, text="two")
    b3 = tk.Button(buttons, text="three")
    
    b1.grid(row=0, column=1)
    b2.grid(row=0, column=2)
    b3.grid(row=0, column=3)
    
    # give empty columns a weight so that the consume
    # all extra space
    buttons.grid_columnconfigure(0, weight=1)
    buttons.grid_columnconfigure(4, weight=1)
    
    root.mainloop()
    
    0 讨论(0)
提交回复
热议问题