Python Tkinter making space between buttons (vertical)

Question:

import tkinter as tk

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


def button_write():
    return


data = tk.Entry(root, width=30, borderwidth=10, font="bold 20", )
data.grid(column=0, row=0, columnspan=4, padx=10, pady=10)
buton1 = tk.Button(root,text="1", padx=40, pady=25, command=button_write)
buton2 = tk.Button(root,text="2", padx=40, pady=25, command=button_write)
buton3 = tk.Button(root,text="3", padx=40, pady=25, command=button_write)
buton4 = tk.Button(root,text="4", padx=40, pady=25, command=button_write)
buton5 = tk.Button(root,text="5", padx=40, pady=25, command=button_write)
buton6 = tk.Button(root,text="6", padx=40, pady=25, command=button_write)
buton7 = tk.Button(root,text="7", padx=40, pady=25, command=button_write)
buton8 = tk.Button(root,text="8", padx=40, pady=25, command=button_write)
buton9 = tk.Button(root,text="9", padx=40, pady=25, command=button_write)
buton0 = tk.Button(root,text="0", padx=40, pady=25, command=button_write)
buton1.grid(row= 1,column=0)
buton2.grid(row= 1,column=1)
buton3.grid(row= 1,column=2)
buton4.grid(row= 1,column=3)


buton5.grid(row= 2,column=0)
buton6.grid(row= 2,column=1)
buton7.grid(row= 2,column=2)
buton8.grid(row= 2,column=3)


buton9.grid(row= 3,column=1)
buton0.grid(row= 3,column=2)

root.mainloop()

I am trying to build a calculator but I don’t know how to make vertical space between buttons. I used pady for that but I didn’t exactly understand how it works so I think it doesn’t work for that don’t worry about that 9 and 0 it is because of photo

Asked By: a python learner

||

Answers:

You need to add the padx and pady args to the grid() calls, e.g.:

buton1.grid(row=1, column=0, padx=10, pady=10)

Setting the padding on the Button widgets just sets their internal padding (makes them wider / taller)

Bonus Round

def button_write(button):
    print(button)  # do whatever you need to do here


for i, n in enumerate(range(9, -1, -1)):
    btn = tk.Button(root, text=n, command=lambda btn=n: button_write(btn))
    y, x = divmod(i, 3)
    btn.grid(row=y, column=x, padx=10, pady=10)
Answered By: JRiggles
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.