I want to make a calculator in Tkinter. So far I have made a grid of buttons with the numbers on it. How would I create an entry box at the top but it is centred in the middle of the grid and so creates a row that is just one entry box?
from tkinter import *
root = Tk()
root.rowconfigure(0, weight=1)
root.columnconfigure(0, weight=1)
button_text = list('1234567890.=')
a = 0
for row_index in range(4):
Grid.rowconfigure(root, row_index, weight=1)
for col_index in range(3):
b = button_text[a]
Grid.columnconfigure(root, col_index, weight=1)
btn = Button(root, text = b)
btn.grid(row=row_index, column=col_index, sticky=N+S+E+W)
a += 1
You can use grid(..., columnwidth=3)
for the Entry
box. To add content to the text, use a StringVar
and add a command
to the buttons. Note that variables in the callback are evaluated when the callback function is called, not when it is defined, thus the c=char
in the lambda
.
from tkinter import *
root = Tk()
var = StringVar()
text = Entry(root, text=var)
text.grid(columnspan=3)
for i, char in enumerate('1234567890.='):
btn = Button(root, text=char, command=lambda c=char: var.set(var.get()+c))
btn.grid(row=1+i//3, column=i%3, sticky=N+S+E+W)
root.mainloop()
Of course, for an actual calculator the callback will be more complex, with special cases for operators, and should delegate to a proper function def
.