Search code examples
pythonpython-3.xtkintercentering

How to center a frame with Tkinter?


I searched a lot about how to center a frame with Tkinter and Python 3.8.

I wrote a code where 4 buttons are in a frame but I don't know how to center the frame in the window. I tried several methods like grid_propagate(0), grid(sticky=""), pack(expand=True), ... But nothing works then.

I am sharing my most recent code there. I hope you can help me.

window = Tk()
frame = Frame(window)
button1 = Button(frame, text="Button 1")
button2 = Button(frame, text="Button 2")
button3 = Button(frame, text="Button 3")
button4 = Button(frame, text="Button 4")

button1.grid(row=0, column=0)
button2.grid(row=0, column=1)
button3.grid(row=1, column=0)
button4.grid(row=1, column=1)
frame.grid_propagate(0)
frame.grid(row=0, column=0, rowspan=2, columnspan=2)

window.mainloop()

Solution

  • It works for me

    Here is the code

    from tkinter import *
    window = Tk()
    frame = Frame(window)
    button1 = Button(frame, text="Button 1")
    button2 = Button(frame, text="Button 2")
    button3 = Button(frame, text="Button 3")
    button4 = Button(frame, text="Button 4")
    
    button1.grid(row=0, column=0)
    button2.grid(row=0, column=1)
    button3.grid(row=1, column=0)
    button4.grid(row=1, column=1)
    frame.place(relx=0.5,rely=0.5,anchor="c")
    
    window.mainloop()