我试图将窗口中心的标签与它下面的两个按钮对齐,也居中。我一直在谷歌搜索并在这里寻找如何做到这一点,我发现网格很有帮助,但它并没有达到我的预期。如果我将每个小部件放在不同的行和列中,它会按预期工作,但是如果我将它们放在不同的行和同一列中,它们只会保持左对齐。我在网格上做错了什么?此外,任何关于我如何改进整体代码的建议都将不胜感激。
我省略了 LoadedMachine 和 CreateMachine 类,因为我觉得不需要它们。如果它们有帮助,我可以编辑问题以添加它们。
class App(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
container = tk.Frame(self)
container.pack(side='top', fill='both', expand=True)
self.frames = {}
for F in (StartPage, LoadedMachine, CreateMachine):
page_name = F.__name__
frame = F(parent=container, controller=self)
self.frames[page_name] = frame
frame.grid(row=0, column=0)
frame.config(bg='white')
self.show_frame('StartPage')
def show_frame(self, page_name):
frame = self.frames[page_name]
frame.tkraise()
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
self.rowconfigure(0, weight=1)
self.rowconfigure(1, weight=1)
self.rowconfigure(2, weight=1)
self.columnconfigure(0, weight=1)
self.columnconfigure(1, weight=1)
self.columnconfigure(2, weight=1)
welcome_label = tk.Label(self, text='Welcome', bg='green', fg='white', font=('Verdana', 80))
welcome_label.grid(row=0, column=1)
loadButton = tk.Button(self, text='Load an existing state machine', command=lambda: controller.show_frame('LoadedMachine'))
loadButton.config(highlightbackground='green', font=('Verdana', 18))
loadButton.grid(row=1, column=1)
createButton = tk.Button(self, text='Create a new state machine', command=lambda: controller.show_frame('CreateMachine'))
createButton.config(highlightbackground='green', font=('Verdana', 18))
createButton.grid(row=2, column=1)
if __name__ == '__main__':
app = App()
app.title('Cognitive State Machine')
app.geometry('800x600')
app.mainloop()
这就是我得到的:
我希望按钮靠得更近,离标签更近。