0
votes

I would like to centre align all my widgets inside a window created by Tkinter. All my widgets are using the grid geometry system. I have tried column and row weights but they do not work for rows and columns that I did not explicitly set. I also tried wrapping the entire window in a Frame and using grid(sticky=NSEW) but it does not make a difference. For my use case, I have more than 50 rows/columns and I would not want to run the weight setting on each of them. This is what I have so far:

root = Tk()
root.minsize(500, 100)
root.rowconfigure(0, weight=1)
root.columnconfigure(0, weight=1)
root.rowconfigure(2, weight=1)
root.columnconfigure(2, weight=1)
root.title('123')
root.iconbitmap(get_res_path('icon.ico'))

status_bar = LabelFrame(root, bd=1, relief=SUNKEN)
status_bar.grid(row=1, column=0, sticky=EW)
status_bar.rowconfigure(1, weight=1)
status_bar.columnconfigure(1, weight=1)
testing_text = Label(status_bar, text='', anchor=W)
testing_text.grid(row=0, column=0, sticky=W)
status_text = Label(status_bar, text='Initializing', anchor=E)
status_text.grid(row=0, column=1, sticky=E)

ver_msg = Label(root, text='123')
ver_msg.grid(row=0, column=0)
Frame(root).pack()

enter image description here

I would like every single element in the window (the text, entry box and button) to be in the middle of the window, and if I drag the window even larger, it is able to adjust itself to stay in the middle.

I have seen many questions but none has given me a working answer.

1
Maybe putting everything inside a frame and then use pack() on the frame might work - Cool Cloud
_tkinter.TclError: cannot use geometry manager grid inside . which already has slaves managed by pack - Billy Cao
Yea post some code so I can know what is going on here - Cool Cloud
'root = Tk() root.minsize(500, 100) root.rowconfigure(0, weight=1) root.columnconfigure(0, weight=1) root.rowconfigure(2, weight=1) root.columnconfigure(2, weight=1) Frame(root).grid(row=1, column=1, sticky=NSEW)' - Billy Cao
Oh thanks for the hint! I got it working as I wish. Would you like to transfer your comments into an answer so that I can mark it as the accepted answer? - Billy Cao

1 Answers

1
votes

The easiest way I can think of here to center the entire app, is to place entire widget inside a frame and then use pack() on the main frame, like:

frame = Frame(root)
frame.pack()

Button(frame, text='This is a button').grid(row=0,column=0)
Label(frame, text='This is a label').grid(row=1,column=0)