Search code examples
pythontkinterwindowframecenter

How to center two frames in one window using tkinter?


All I want to do is center the top frame in this window, and it seems like it should be painfully simple, but after a week I still can't figure it out.

I have tried changing this from pack to grid. I've tried using expand, fill, sticky, and side. None of them work in any of their iterations or combinations.

What is happening here that is causing it to stick to the left of the screen and how can I just center it?

Here is an image of the tkinter GUI

import tkinter as tk

root = tk.Tk()

frame1 = tk.Frame(root, bg='gold')
frame2 = tk.Frame(root)

frame1label = tk.Label(frame1, bg='gold', text='Top label')
frame1label.grid(row=0)

frame2label = tk.Label(frame2, text='Bottom label')
frame2label.pack()

frame1.pack(fill=tk.X)
frame2.pack()

root.mainloop()

Solution

  • You have to tell widgets to expand if the grid resizes. You can do that with columnconfigure. Using the sticky parameter you can tell the widget how to react. Have a look at Handling Resize at this site: https://tkdocs.com/tutorial/grid.html

    import tkinter as tk
    
    root = tk.Tk()
    
    frame1 = tk.Frame(root, bg='gold')
    frame1.pack(fill=tk.X)
    frame1.columnconfigure(0, weight=1)
    frame2 = tk.Frame(root)
    frame2.pack()
    
    frame1label1 = tk.Label(frame1, bg='gold', text='Top label')
    frame1label1.grid(row=0, column=0)
    frame2label = tk.Label(frame2, text='Bottom label')
    frame2label.pack()
    
    root.mainloop()