Search code examples
pythontkintertkinter-layout

Is there a way that I can center a grid in tkinter?


My idea is to make a GUI with a grid and I want that the grid it self to be centered in the window.

root = Tk()
root.state('zoomed')
telaInicial = Frame(root)

botaoNovoAluno = Button(telaInicial, text = "Novo aluno", padx = 5, pady = 5)
botaoEliminarAluno = Button(telaInicial, text = "Eliminar aluno", padx = 5, pady = 5)
botaoAvaliacaoAluno = Button(telaInicial, text = "Avaliaçao aluno", padx = 5, pady = 5)
botaoVerDados = Button(telaInicial, text = "Ver dados", padx = 5, pady = 5)

botaoNovoAluno.grid(row = 0, column = 0, padx = 10, pady = 10)
botaoEliminarAluno.grid(row = 0, column = 2, padx = 10, pady = 10)
botaoAvaliacaoAluno.grid(row = 1, column = 1, padx = 10, pady = 10)
botaoVerDados.grid(row = 2, column = 1, padx = 10, pady = 10)

raise_frame(telaInicial)
root.mainloop()

note: Sorry for the English, its not my mother language.


Solution

  • The simple solution is to place your frame at row and column 1 and then apply weights to column/row 0 and 2. This will keep everything in your frame centered.

    Here is an example:

    import tkinter as tk
    
    root = tk.Tk()
    root.state('zoomed')
    telaInicial = tk.Frame(root)
    telaInicial.grid(row=1, column=1)
    root.columnconfigure(0, weight=1)
    root.columnconfigure(2, weight=1)
    root.rowconfigure(0, weight=1)
    root.rowconfigure(2, weight=1)
    
    botaoNovoAluno = tk.Button(telaInicial, text="Novo aluno", padx=5, pady=5)
    botaoEliminarAluno = tk.Button(telaInicial, text="Eliminar aluno", padx=5, pady=5)
    botaoAvaliacaoAluno = tk.Button(telaInicial, text="Avaliaçao aluno", padx=5, pady=5)
    botaoVerDados = tk.Button(telaInicial, text="Ver dados", padx=5, pady=5)
    
    botaoNovoAluno.grid(row=0, column=0, padx=10, pady=10)
    botaoEliminarAluno.grid(row=0, column=2, padx=10, pady=10)
    botaoAvaliacaoAluno.grid(row=1, column=1, padx=10, pady=10)
    botaoVerDados.grid(row=2, column=1, padx=10, pady=10)
    
    root.mainloop()
    

    Results:

    enter image description here

    That said you may want to take some time to read PEP8. Using a standard naming convention will make your code easier to read for everyone.