Free cookie consent management tool by TermsFeed

Volume Calculator in Python with Graphical Interface

 

In this tutorial, we are going to create a volume calculator with a graphical interface using the Tkinter library in Python. The calculator will allow the user to enter the radius value and will see the volume of the sphere and cube calculated automatically.

Introduction

In this tutorial, we are going to create a volume calculator with a graphical interface using Tkinter. The interface will have a field for the user to enter the radius value, and the program will automatically calculate the volume of the sphere and cube based on this value.

Step 1: Import Required Libraries

from tkinter import *
from tkinter import ttk
from PIL import ImageTk, Image
import locale

In this step, we import the necessary libraries: `tkinter` for creating the GUI, `ttk` for themed widget support, `PIL` for handling images, and `locale` for setting locale-specific formatting.

Step 2: Set Locale and Define Colors

locale.setlocale(locale.LC_ALL, 'en_US')

co1 = "#feffff"  # white
co2 = "#111212"  # black
co3 = "#38576b"  # value
background = "#f2f5f3"


We set the locale to 'en_US' for proper number formatting and define color codes for the user interface.

Step 3: Define the Calculate Function

def calculate_volume():
    radius = float(all_values)
    sphere_volume = (4/3) * 3.14159 * radius**3
    label_sphere.config(text=f"The volume of the sphere is: {format_number(sphere_volume, 'cubic meter')}")

    side = float(all_values)
    cube_volume = side**3
    label_cube.config(text=f"The volume of the cube is: {format_number(cube_volume, 'cubic meter')}")


This function calculates the volume of a sphere and a cube based on the provided radius. It uses the formula for the volume of a sphere and cube. The results are displayed on the GUI labels.

Step 4: Define Number Formatting Function

def format_number(number, unit):
    return "{:,.2f} {}".format(number, unit)


This function formats a number with two decimal places and appends a unit label to it.

Step 5: Define Key Event Handler Function

def handle_key(event):
    global all_values
    if event.char.isdigit() or event.char == ".":
        all_values = all_values + str(event.char)
        entry_radius.delete(0, END)
        entry_radius.insert(0, all_values)
        calculate_volume()

    if event.keysym == "BackSpace":
        # Delete the last character
        all_values = all_values[:-1]
        entry_radius.delete(0, END)
        entry_radius.insert(0, all_values)
        calculate_volume()


This function handles keyboard events for number input and backspace. It updates the value in the Entry field, triggers volume calculation, and displays the results.

Step 6: Create the Main Window

window = Tk()
window.title('')
window.geometry('400x200')
window.configure(bg=background)


Here, we create the main window, set its title, dimensions, and background color.

Step 7: Define GUI Style

style = ttk.Style(window)
style.theme_use("clam")


We define the style of the GUI elements using the ttk theme.

Step 8: Create Logo and Result Frames

frame_logo = Frame(window, width=400, height=56, bg=background, pady=0, padx=0, relief="flat")
frame_logo.grid(row=0, column=0, sticky="nw")

frame_result = Frame(window, width=400, height=150, bg=background, pady=0, padx=0, relief="flat")
frame_result.grid(row=1, column=0, sticky="nw")


We create two frames for the logo and result sections of the GUI.

Step 9: Load and Display Logo

app_logo_image = Image.open('logo.png')
app_logo_image = app_logo_image.resize((40, 40))
app_logo_image = ImageTk.PhotoImage(app_logo_image)
app_logo = Label(frame_logo, image=app_logo_image, text="Volume Calculator", width=850, compound="left", anchor="nw", font=('Verdana 15'), bg=background, fg=co2)
app_logo.place(x=5, y=0)


We load and display the logo image using the `PIL` and `ImageTk` libraries.

Step 10: Create and Bind Entry and Labels

all_values = ""
value_text = StringVar()

frame_result.bind("<KeyRelease>", handle_key)

entry_radius = ttk.Entry(frame_result, textvariable=value_text, width=10, font=('Tahoma 25 bold'), justify='center')
entry_radius.place(x=10, y=0)
entry_radius.bind("<KeyRelease>", handle_key)

label_sphere = Label(frame_result, text='', width=850, compound="left", anchor="nw", font=('Calibri 12 '), bg=background, fg=co2)
label_sphere.place(x=10, y=70)

label_cube = Label(frame_result, text='', width=850, compound="left", anchor="nw", font=('Calibri 12 '), bg=background, fg=co2)
label_cube.place(x=10, y=90)

We create an entry field for the radius, bind key events, and create labels to display the sphere and cube volume results.

Step 11: Run the GUI Application

window.mainloop()


Finally, we start the GUI event loop to run the application.

Congratulations! You've created a Volume Calculator GUI using Python and Tkinter. The calculator calculates the volume of a sphere and cube based on the provided radius and displays the results in a user-friendly interface. This tutorial guides you through each step of creating the calculator, from importing libraries to defining functions and creating the graphical interface.

Post a Comment

0 Comments

Close Menu