有没有办法让我在 tkinter 中将网格居中?

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

我的想法是制作一个带有网格的 GUI,我希望网格本身位于 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()

注意:抱歉是英语,它不是我的母语。

简单的解决方案是将框架放在第 1 行和第 1 列,然后对 column/row 0 和 2 应用权重。这将使框架中的所有内容都居中。

这是一个例子:

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()

结果:

那是说您可能需要花一些时间阅读 PEP8。使用标准的命名约定将使您的代码更易于所有人阅读。