[Tkinter-discuss] Centering grid inside a frame

Bryan Oakley bryan.oakley at gmail.com
Thu Jun 25 12:49:14 CEST 2015


Use an empty row and column surrounding your other widgets, and give those
rows and columns a weight. That is, leave row and column 0 empty, and the
row and column below and to the right of all the other widgets empty. With
a non-zero weight, and with the non-empty rows/columns with a default
weight of zero, the empty rows and columns  will be given all extra room,
effectively centering the other widgets.

from Tkinter import *

tk = Tk()
Button(tk, text="button1").grid(row=1, column=1, sticky=NSEW)
Button(tk, text="button2").grid(row=1, column=2, sticky=NSEW)
Button(tk, text="button3").grid(row=2, column=1, sticky=NSEW)
Button(tk, text="button4").grid(row=2, column=2, sticky=NSEW)

tk.grid_rowconfigure(0, weight=1)
tk.grid_rowconfigure(3, weight=1)
tk.grid_columnconfigure(0, weight=1)
tk.grid_columnconfigure(3, weight=1)

tk.mainloop()


On Thu, Jun 25, 2015 at 5:17 AM, Vasilis Vlachoudis <
Vasilis.Vlachoudis at cern.ch> wrote:

>  Hi all,
>
> I want to centre a grid layout (with fixed size) inside a frame
> e.g. if I do the following
>
> tk = Tk()
> Button(tk, text="button1").grid(row=0, column=0, sticky=NSEW)
> Button(tk, text="button2").grid(row=0, column=1, sticky=NSEW)
> Button(tk, text="button3").grid(row=1, column=0, sticky=NSEW)
> Button(tk, text="button4").grid(row=1, column=1, sticky=NSEW)
> tk.mainloop()
>
> on python 2.7 I get the 4 buttons anchored on the NW corner of the tk frame
> If I resize the window the buttons are stuck there.
>
> I know that I could add an additional frame and use the place manager like
> f = Frame(tk)
> f.place(relx=0.5, rely=0.5, anchor=CENTER)
> and change all buttons to belong to f.
>
> However on python 2.4 I get the 4 buttons perfectly centred in the tk frame
> without the additional f-frame.
> Is there a special flag that I could do the centering without the need of
> the extra frame.
>
> Thanks in advance
> Vasilis
>
>
> _______________________________________________
> Tkinter-discuss mailing list
> Tkinter-discuss at python.org
> https://mail.python.org/mailman/listinfo/tkinter-discuss
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tkinter-discuss/attachments/20150625/975c9f90/attachment.html>


More information about the Tkinter-discuss mailing list