Python GUI for a Basic Calculator Application

Posted by

Simple Calculator App GUI in Python

Simple Calculator App GUI in Python

In this tutorial, we will create a simple calculator app with a graphical user interface (GUI) using Python.

Prerequisites

Before we start, make sure you have Python installed on your computer. You can download Python from here.

Step 1: Install tkinter

We will use the tkinter library to create the GUI for our calculator app. If you don’t have tkinter installed, you can install it using the following command:

pip install tk

Step 2: Create the Calculator App

Now, let’s create the code for our calculator app. Copy and paste the following code into a new Python file (e.g., calculator.py):

	from tkinter import *
	
	# create the main window
	root = Tk()
	root.title("Simple Calculator")
	
	# create an entry widget to display the input
	entry = Entry(root, width=20, borderwidth=5)
	entry.grid(row=0, column=0, columnspan=4)
	
	# function to add a number to the input
	def add_number(number):
	    current = entry.get()
	    entry.delete(0, END)
	    entry.insert(0, current + number)
	
	# function to clear the input
	def clear():
	    entry.delete(0, END)
	
	# function to calculate the result
	def calculate():
	    try:
	        result = eval(entry.get())
	        entry.delete(0, END)
	        entry.insert(0, str(result))
	    except:
	        entry.delete(0, END)
	        entry.insert(0, "Error")
	
	# create buttons for numbers and operations
	for i in range(1, 10):
	    button = Button(root, text=str(i), command=lambda i=i: add_number(str(i)))
	    button.grid(row=1+(i-1)//3, column=(i-1)%3)
	
	operations = ["+", "-", "*", "/", "=", "C"]
	for i, operation in enumerate(operations):
	    button = Button(root, text=operation, command=lambda operation=operation: 
	                    clear() if operation == "C" else calculate())
	    button.grid(row=1+i, column=3)
	
	# start the GUI main loop
	root.mainloop()
	

Step 3: Run the Calculator App

Save the Python file and run it using the following command:

python calculator.py

You should see the calculator app with a simple GUI that allows you to perform basic calculations. Try entering some numbers and operations to see the app in action!

Conclusion

Congratulations! You have successfully created a simple calculator app with a GUI using Python and the tkinter library. Feel free to customize the app further by adding more functionality or improving the design. Happy coding!