Create a Simple Calculator Using Tkinter in Python
To create a calculator using
tkinter in Python, you build a window with buttons for digits and operations, and a display area using Entry. You then connect button clicks to functions that update the display or calculate results using eval() safely.Syntax
Here is the basic syntax to create a Tkinter window with buttons and an entry display for a calculator:
Tk(): Creates the main window.Entry(): Creates the display area for input and results.Button(): Creates buttons for digits and operations.grid(): Places widgets in a grid layout.- Functions handle button clicks and calculations.
python
from tkinter import Tk, Entry, Button def on_click(char): # Update display with clicked character pass def calculate(): # Evaluate expression and update display pass root = Tk() root.title('Calculator') display = Entry(root, width=16, font=('Arial', 24), borderwidth=2, relief='ridge') display.grid(row=0, column=0, columnspan=4) # Example button btn_1 = Button(root, text='1', command=lambda: on_click('1')) btn_1.grid(row=1, column=0) root.mainloop()
Example
This example shows a complete simple calculator with buttons for digits 0-9, operations +, -, *, /, a clear button, and an equals button to calculate the result.
python
from tkinter import Tk, Entry, Button def on_click(char): current = display.get() display.delete(0, 'end') display.insert(0, current + char) def clear(): display.delete(0, 'end') def calculate(): try: result = eval(display.get()) display.delete(0, 'end') display.insert(0, str(result)) except Exception: display.delete(0, 'end') display.insert(0, 'Error') root = Tk() root.title('Calculator') display = Entry(root, width=16, font=('Arial', 24), borderwidth=2, relief='ridge') display.grid(row=0, column=0, columnspan=4) buttons = [ ('7', 1, 0), ('8', 1, 1), ('9', 1, 2), ('/', 1, 3), ('4', 2, 0), ('5', 2, 1), ('6', 2, 2), ('*', 2, 3), ('1', 3, 0), ('2', 3, 1), ('3', 3, 2), ('-', 3, 3), ('0', 4, 0), ('.', 4, 1), ('C', 4, 2), ('+', 4, 3), ('=', 5, 0, 4) ] for btn in buttons: text = btn[0] row = btn[1] col = btn[2] colspan = btn[3] if len(btn) == 4 else 1 if text == 'C': action = clear elif text == '=': action = calculate else: action = lambda char=text: on_click(char) b = Button(root, text=text, width=4, height=2, font=('Arial', 18), command=action) b.grid(row=row, column=col, columnspan=colspan) root.mainloop()
Output
A window opens showing a calculator interface with buttons 0-9, +, -, *, /, C, ., and =. Clicking buttons updates the display, C clears it, and = calculates the result.
Common Pitfalls
Common mistakes when creating a Tkinter calculator include:
- Not using
lambdacorrectly in button commands, causing all buttons to send the same value. - Using
eval()without error handling, which can crash the program on invalid input. - Not clearing the display before inserting new text, causing input to append incorrectly.
- Forgetting to set
columnspanfor the equals button to span multiple columns.
python
from tkinter import Tk, Button, Entry root = Tk() display = Entry(root) display.grid(row=0, column=0, columnspan=4) # Wrong: lambda captures late binding, all buttons send '9' for i in range(10): Button(root, text=str(i), command=lambda: display.insert('end', str(i))).grid(row=1, column=i) # Right: lambda with default argument captures current i for i in range(10): Button(root, text=str(i), command=lambda x=i: display.insert('end', str(x))).grid(row=2, column=i) root.mainloop()
Output
A window with two rows of buttons 0-9. The first row inserts '9' for all buttons (wrong). The second row inserts correct digits 0-9 (right).
Quick Reference
Tips for building a Tkinter calculator:
- Use
Entryfor display input/output. - Use
Buttonwidgets withcommand=lambdato handle clicks. - Use
grid()for layout to organize buttons in rows and columns. - Use
eval()carefully with try-except to calculate expressions. - Clear display before inserting new text to avoid appending errors.
Key Takeaways
Use Tkinter's Entry widget as the calculator display and Button widgets for input.
Connect buttons to functions using lambda to pass the correct character on click.
Use eval() inside try-except to safely compute the expression from the display.
Clear the display before inserting new input to avoid concatenation errors.
Organize buttons with grid layout for a clean calculator interface.