Weight Conversion GUI using Tkinter


Graphical User Interfaces (GUIs) are an integral part of modern software applications, providing an interactive and user-friendly experience. In this tutorial, we will explore how to create a Weight Conversion GUI using Tkinter, a popular Python library for creating GUI applications.

Our Weight Conversion GUI will allow users to easily convert weights between different units such as kilograms (kg), pounds (lb), and ounces (oz).

Let's start by setting up the project. Open your favorite text editor or integrated development environment (IDE) and create a new Python script file. Let's name it weight_converter.py.

Importing Required Modules

In our weight_converter.py file, we'll begin by importing the necessary modules. Tkinter provides the core functionality for building GUIs, so we need to import it 

import tkinter as tk
from tkinter import ttk

Here, we import the tkinter module as tk and the ttk module, which provides themed widgets, also from tkinter.

Creating the GUI Window

Next, we'll define a function called create_gui that will create our GUI window. This function will be responsible for initializing the window, setting its properties, and starting the main event loop −

def create_gui():
   # Create the main window
   window = tk.Tk()
   window.title("Weight Conversion")
   window.geometry("400x200")

   # Add code here

   # Start the GUI event loop
   window.mainloop()

# Call the create_gui function
create_gui()

In the create_gui function, we create an instance of the Tk class, which represents the main window of our GUI application. We set the window's title to "Weight Conversion" and its dimensions to 400 x 200 pixels. Finally, we start the GUI event loop using the mainloop method.

By calling the create_gui function, we initiate the creation of our GUI window when the script is executed.

Adding GUI Components

With the GUI window set up, let's move on to adding the necessary GUI components. We'll include labels, input fields, and a button for the conversion functionality.

def create_gui():
   # ...

   # Create the labels
   label_kg = ttk.Label(window, text="Kilograms:")
   label_kg.grid(column=0, row=0, padx=10, pady=10)

   label_lb = ttk.Label(window, text="Pounds:")
   label_lb.grid(column=0, row=1, padx=10, pady=10)

   label_oz = ttk.Label(window, text="Ounces:")
   label_oz.grid(column=0, row=2, padx=10, pady=10)

   # Create the entry fields
   entry_kg = ttk.Entry(window)
   entry_kg.grid(column=1, row=0, padx=10, pady=10)

   entry_lb = ttk.Entry(window)
   entry_lb.grid(column=1, row=1, padx=10, pady=10)

   entry_oz = ttk.Entry(window)
   entry_oz.grid(column=1, row=2, padx=10, pady=10)

   # Create the conversion button
   button_convert = ttk.Button(window, text="Convert")
   button_convert.grid(column=0, row=3, columnspan=2, padx=10, pady=10)

   # Add code here

In the code above, we create three ttk.Label instances to display the names of the weight units. We use the grid method to position them in the first column of the window.

Next, we create three ttk.Entry instances for users to input the weight values. We use the grid method to position them in the second column of the window.

Lastly, we create a ttk.Button instance labeled "Convert" to trigger the weight conversion process. The button spans across two columns and is positioned in the fourth row.

The basic structure of our Weight Conversion GUI is now in place. In the next part of this tutorial, we will implement the weight conversion functionality and make the GUI fully functional.

Implementing the Conversion Functionality

Now that we have the GUI components set up, let's implement the weight conversion functionality when the "Convert" button is clicked.

def convert_weight():
   try:
      kg = float(entry_kg.get())
      lb = kg * 2.20462
      oz = kg * 35.274

      entry_lb.delete(0, tk.END)
      entry_lb.insert(0, round(lb, 2))

      entry_oz.delete(0, tk.END)
      entry_oz.insert(0, round(oz, 2))
   except ValueError:
      # Handle invalid input
      pass

def create_gui():
   # ...

   button_convert = ttk.Button(window, text="Convert", command=convert_weight)
   # ...

   # ...

In the code above, we define a function called convert_weight that will perform the conversion calculations. We retrieve the weight in kilograms from the entry_kg input field, convert it to pounds and ounces using the conversion factors, and update the respective entry fields.

We use the get method on the entry_kg object to retrieve the value entered by the user as a string. We convert it to a float using the float function.

Next, we calculate the equivalent weight in pounds and ounces by multiplying the weight in kilograms by the respective conversion factors.

To display the converted weights, we first clear the contents of the entry_lb and entry_oz fields using the delete method with the tk.END argument. Then, we insert the rounded values of lb and oz into their respective entry fields using the insert method.

We wrap the conversion code in a try-except block to handle the case of invalid input. If the user enters a non-numeric value, a ValueError will be raised. In this case, we simply pass and no conversion is performed.

Lastly, we assign the convert_weight function as the command for the "Convert" button using the command parameter. This ensures that the function is executed when the button is clicked.

Running the Application

Save the weight_converter.py file and open a terminal or command prompt. Navigate to the directory where the file is located and execute the following command 

python weight_converter.py

The GUI window should appear on your screen. Enter a weight in kilograms, click the "Convert" button, and the equivalent weights in pounds and ounces will be displayed.

Following are some Sample Output examples for better understanding. When you run the weight_converter.py script and interact with the GUI window, here's an example of what you can expect:

  • Input  5 kilograms

  • Output 

    • Pounds: 11.02 lbs

    • Ounces: 176.37 oz

  • Input  2.5 kilograms

  • Output 

    • Pounds: 5.51 lbs

    • Ounces: 88.18 oz

These output examples demonstrate the conversion of weights in kilograms to pounds and ounces using the Weight Conversion GUI.

Conclusion

We've built a Weight Conversion GUI using Tkinter in Python. We started by setting up the project, importing the necessary modules, and creating the GUI window. Then, we added the labels, input fields, and a button for weight conversion.

We implemented the weight conversion functionality by retrieving the input value, performing the necessary calculations, and updating the display accordingly. We also handled invalid input gracefully.

Updated on: 16-Aug-2023

137 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements