Building a Calculator with Python Tkinter
Python Tkinter is a library that provides a simple way to create GUI applications. In this tutorial, we will be building a basic calculator using Python Tkinter.
Step 1: Importing tkinter
First, we need to import the tkinter library in our Python script.
“`python
from tkinter import *
“`
Step 2: Creating the calculator window
Next, we will create a window for our calculator using the Tkinter Tk()
function.
“`python
root = Tk()
root.title(“Python Calculator”)
“`
Step 3: Adding the display
We will add a text box to display the numbers and calculations.
“`python
display = Entry(root, justify=”right”)
display.grid(row=0, column=0, columnspan=4)
“`
Step 4: Creating the buttons
We will create buttons for each number, operator, and the equal sign.
“`python
buttons = [
‘7’, ‘8’, ‘9’, ‘/’,
‘4’, ‘5’, ‘6’, ‘*’,
‘1’, ‘2’, ‘3’, ‘-‘,
‘C’, ‘0’, ‘=’, ‘+’
]
row = 1
col = 0
for button in buttons:
Button(root, text=button, width=5, height=2).grid(row=row, column=col)
col += 1
if col > 3:
col = 0
row += 1
“`
Step 5: Adding functionality
Finally, we will add functionality to the buttons using the command
attribute.
“`python
def button_click(value):
current = display.get()
display.delete(0, END)
display.insert(0, current + value)
for button in buttons:
if button == ‘C’:
Button(root, text=button, width=5, height=2, command=lambda: display.delete(0, END)).grid(row=row, column=col)
elif button == ‘=’:
Button(root, text=button, width=5, height=2, command=lambda: display.insert(END, eval(display.get()))).grid(row=row, column=col)
else:
Button(root, text=button, width=5, height=2, command=lambda value=button: button_click(value)).grid(row=row, column=col)
col += 1
if col > 3:
col = 0
row += 1
“`
And that’s it! You have now built a simple calculator using Python Tkinter. Feel free to customize and enhance the calculator with more functionalities.