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 there are multiple columns in a row, objects in them end up left-aligned:
while I wish for them to stay in the center (while maintaining size).
Code excerpt:
from Tkinter import N,W,S,E,Tk
import ttk
import Tkinter as tkinter
root = Tk()
mainframe = ttk.Frame(root)
mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
mainframe.columnconfigure(0, weight=1)
mainframe.rowconfigure(0, weight=1)
tv_town_fr = ttk.Frame(mainframe)
tv_town_fr.grid(row=3, sticky=(W,E))
tv_town_add = ttk.Button(tv_town_fr,text="+",width=4)
tv_town_add.grid(row=1,column=1)
tv_town_edit = ttk.Button(tv_town_fr,text="*",width=4)
tv_town_edit.grid(row=1,column=2)
tv_town_del = ttk.Button(tv_town_fr,text="-",width=4)
tv_town_del.grid(row=1,column=3)
tv_town_up = ttk.Button(tv_town_fr,text=u"↑",width=4)
tv_town_up.grid(row=1,column=4)
tv_town_down = ttk.Button(tv_town_fr,text=u"↓",width=4)
tv_town_down.grid(row=1,column=5)
tv_query_fr = ttk.Frame(mainframe)
tv_query_fr.grid(row=6, sticky=(W,E))
tv_query_add = ttk.Button(tv_query_fr,text="+",width=5)
tv_query_add.grid(row=1,column=1)
tv_query_edit = ttk.Button(tv_query_fr,text="*",width=5)
tv_query_edit.grid(row=1,column=2)
tv_query_del = ttk.Button(tv_query_fr,text="-",width=5)
tv_query_del.grid(row=1,column=3)
tv_query_up = ttk.Button(tv_query_fr,text=u"↑",width=5)
tv_query_up.grid(row=1,column=4)
tv_query_down = ttk.Button(tv_query_fr,text=u"↓",width=5)
tv_query_down.grid(row=1,column=5)
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With