无法理解 Tkinter 网格系统

Cant understand Tkinter Grid System

我刚开始学习 Tkinter,我正在尝试制作一个计算器,但按钮不会按我想要的方式放置。我不明白网格的概念,我的行是正确的,但列乱七八糟,并且之间有很大的差距。我需要帮助来修复列,我就是不明白

from tkinter import *

root = Tk()
root.title("Simple Calculator")

input_field = Entry(root, borderwidth = 5, fg = "black", width = 40)

button_1 = Button(root, text = "1")
button_2 = Button(root, text = "2")
button_3 = Button(root, text = "3")
button_4 = Button(root, text = "4")
button_5 = Button(root, text = "5")
button_6 = Button(root, text = "6")
button_7 = Button(root, text = "7")
button_8 = Button(root, text = "8")
button_9 = Button(root, text = "9")
button_0 = Button(root, text = "0")

button_1.grid(row = 1, column = 0)
button_2.grid(row = 1, column = 1)
button_3.grid(row = 1, column = 2)
button_4.grid(row = 2, column = 1)
button_5.grid(row = 2, column = 2)
button_6.grid(row = 2, column = 3)
button_7.grid(row = 3, column = 1)
button_8.grid(row = 3, column = 2)
button_9.grid(row = 3, column = 3)
button_0.grid(row = 4, column = 0)

input_field.grid(row = 0, column = 0, columnspan = 3,  padx = 30, pady = 30)

root = mainloop()

您可以在网格中使用粘性边界 你也可以使用 rowconfigure 和 columncongifure

您可以为按钮创建不同的框架

你应该阅读这篇文章https://tkdocs.com/tutorial/grid.html

你可以试试这个:-

from tkinter import*
root = Tk()
root.title("Simple Calculator")

input_field = Entry(root, borderwidth = 5, fg = "black", width = 40)
input_field.pack()
frame = Frame(root)
frame.pack(expand=True,fill=BOTH)
for i in range(1,4):
    frame.rowconfigure(i,weight=1)
for i in range(0,4):
    frame.columnconfigure(i,weight=1)

button_1 = Button(frame, text = "1")
button_2 = Button(frame, text = "2")
button_3 = Button(frame, text = "3")
button_4 = Button(frame, text = "4")
button_5 = Button(frame, text = "5")
button_6 = Button(frame, text = "6")
button_7 = Button(frame, text = "7")
button_8 = Button(frame, text = "8")
button_9 = Button(frame, text = "9")
button_0 = Button(frame, text = "0")

button_1.grid(row = 1, column = 0,sticky=NSEW)
button_2.grid(row = 1, column = 1,sticky=NSEW)
button_3.grid(row = 1, column = 2,sticky=NSEW)
button_4.grid(row = 2, column = 1,sticky=NSEW)
button_5.grid(row = 2, column = 2,sticky=NSEW)
button_6.grid(row = 2, column = 3,sticky=NSEW)
button_7.grid(row = 3, column = 1,sticky=NSEW)
button_8.grid(row = 3, column = 2,sticky=NSEW)
button_9.grid(row = 3, column = 3,sticky=NSEW)
button_0.grid(row = 4, column = 0,sticky=NSEW)



root = mainloop()