Search code examples
pythontkinterttk

How can I center a button on a frame in ttk?


I have trouble getting a button centered on a frame with ttk: enter image description here

Here is the code for the example above:

from tkinter import *
from tkinter.ttk import *

root = Tk()
root.title("button on a frame")

l = Label(root, text="why wont my button")
l2 = Label(root, text="on a frame center?")
l.grid(row=0, column=0)
l2.grid(row=1, column=1)

myStyle = Style()
myStyle.configure("green.TFrame", background="green")

bottomFrame = Frame(root, style="green.TFrame")
bottomFrame.grid(row=11, columnspan=2, sticky=E+W, pady=5)

runButton = Button(bottomFrame, text="Run")
runButton.grid(pady=5)

root.mainloop()

If I add a button without the frame underneath, it gets centered.


Solution

  • You need to set weight for rows and columns of your Frame.

    bottomFrame = Frame(root, style="green.TFrame")
    bottomFrame.grid(row=11, columnspan=2, sticky=E+W+N+S, pady=5)
    bottomFrame.grid_columnconfigure(0, weight=1)
    bottomFrame.grid_rowconfigure(0, weight=1)
    
    runButton = Button(bottomFrame, text="Run")
    runButton.grid(pady=5)
    

    weight (column):

    A relative weight used to distribute additional space between columns. A column with the weight 2 will grow twice as fast as a column with weight 1. The default is 0, which means that the column will not grow at all.

    weight (row):

    A relative weight used to distribute additional space between rows. A row with the weight 2 will grow twice as fast as a row with weight 1. The default is 0, which means that the row will not grow at all.