Home > other >  Cant understand Tkinter Grid System
Cant understand Tkinter Grid System

Time:05-09

I just started learning Tkinter and I'm trying to make a calculator but the buttons wont position as i want. I dont understand the grid concept, my rows are right but columns are messed up and have massive gaps between. I need help in fixing the columns, I just dont get it

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

CodePudding user response:

you can use sticky perimeter in grid And you can also use rowconfigure and columncongifure

You can to create different frame for buttons

You should read this https://tkdocs.com/tutorial/grid.html

You can try this:-

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