How to Build a Currency Converter GUI Application with Python and Tkinter

Have you ever needed to quickly convert one currency to another? With Python and the Tkinter library, it‘s easy to build your own graphical user interface (GUI) application to do just that. In this step-by-step tutorial, we‘ll walk through how to create a basic currency converter app from scratch.

By the end, you‘ll have a functional desktop application that can convert between over 100 world currencies using real-time exchange rate data. More importantly, you‘ll gain an understanding of the fundamentals of building GUIs in Python. This knowledge will empower you to create your own user-friendly interfaces for any Python project.

Why build a GUI?

Command line interfaces are great for many tasks, but sometimes you need something more user-friendly and interactive. That‘s where graphical user interfaces come in. With a well-designed GUI, users can interact with your application in an intuitive way without needing to understand the intricacies of the underlying code.

Currency conversion is a great example of a task that benefits from a GUI. While you could certainly write a script to convert currencies using command line arguments, a visual interface makes the process much simpler. Users can simply select their currencies, enter an amount, and click a button to get the result. No need to memorize ISO currency codes or command line options.

Tools you‘ll need

To follow along with this tutorial, you‘ll need:

  • Python 3.7 or higher installed on your machine
  • A basic understanding of Python syntax and concepts
  • The Tkinter library (included with Python)
  • An API key from the Free Currency Converter API (more on this later)

We‘ll also be using the requests library to interact with the currency conversion API. You can install it from the command line with:

pip install requests

Setting up the project

To get started, create a new directory for your project and open it in your favorite code editor. We‘ll be working with two Python files:

  1. main.py will contain the code for the GUI application.
  2. api.py will handle interaction with the currency conversion API.

Let‘s start with api.py. Here‘s the code to set up the API client:

import requests

class CurrencyConverter:
    def __init__(self, api_key):
        self.api_key = api_key
        self.base_url = f"https://free.currconv.com/api/v7/convert?apiKey={api_key}"

    def convert(self, from_currency, to_currency, amount):
        query = f"{from_currency}_{to_currency}"
        response = requests.get(f"{self.base_url}&q={query}&compact=ultra")
        data = response.json()

        if query not in data:
            raise ValueError(f"Unable to convert from {from_currency} to {to_currency}")

        rate = data[query]
        converted_amount = amount * rate

        return converted_amount

This class takes an API key in its constructor and provides a convert method to convert from one currency to another. It uses the requests library to send a GET request to the Free Currency Converter API and returns the converted amount.

Note that you‘ll need to sign up for a free API key at https://free.currencyconverterapi.com/ to use this code. Once you have your key, save it in a file called config.py in your project directory:

API_KEY = "your-api-key-here"

With the API client set up, we can move on to building the GUI.

Creating the GUI window

The first step in any Tkinter application is to create the main window. This serves as the foundation for all the other widgets we‘ll add. Here‘s the basic setup in main.py:

import tkinter as tk
from tkinter import ttk
import config
from api import CurrencyConverter

class CurrencyConverterGUI:
    def __init__(self, converter):
        self.converter = converter

        self.window = tk.Tk()
        self.window.title("Currency Converter")
        self.window.geometry("350x200")

        self.create_gui()

        self.window.mainloop()

    def create_gui(self):
        pass

if __name__ == "__main__":
    converter = CurrencyConverter(config.API_KEY)
    CurrencyConverterGUI(converter)

This code creates a CurrencyConverterGUI class that takes a CurrencyConverter instance in its constructor. It sets up the main application window with a title and size, then calls a create_gui method to build the widgets (which we‘ll implement next). Finally, it starts the Tkinter event loop with mainloop().

The if __name__ == "__main__": block at the bottom ensures that the GUI is only created if this file is run directly, not imported as a module. It creates an instance of CurrencyConverter using the API key from config.py, then passes it to the CurrencyConverterGUI constructor.

If you run main.py now, you should see a blank window with the title "Currency Converter". Let‘s add some widgets to make it functional.

Adding widgets

The GUI will consist of the following elements:

  • Two dropdown menus to select the "from" and "to" currencies
  • An entry field for the amount to convert
  • A "Convert" button to perform the conversion
  • A label to display the result

We can create each of these widgets in the create_gui method. Here‘s the updated code:

def create_gui(self):
    # Currency selection dropdowns
    currency_frame = ttk.Frame(self.window)

    from_label = ttk.Label(currency_frame, text="From:")
    from_label.grid(row=0, column=0, sticky="w", padx=5, pady=5)
    to_label = ttk.Label(currency_frame, text="To:")
    to_label.grid(row=0, column=1, sticky="w", padx=5, pady=5)

    self.from_currency = tk.StringVar()
    from_dropdown = ttk.Combobox(currency_frame, textvariable=self.from_currency)
    from_dropdown.grid(row=1, column=0, padx=5, pady=5)

    self.to_currency = tk.StringVar()  
    to_dropdown = ttk.Combobox(currency_frame, textvariable=self.to_currency)
    to_dropdown.grid(row=1, column=1, padx=5, pady=5)

    # Populate dropdowns with currency options
    currencies = ["USD", "EUR", "GBP", "JPY", "CAD", "AUD", "CHF", "CNY", "HKD", "SGD"]
    from_dropdown["values"] = currencies
    to_dropdown["values"] = currencies

    from_dropdown.current(0)  # Default to USD
    to_dropdown.current(1)  # Default to EUR

    currency_frame.pack(pady=10)

    # Amount entry      
    amount_frame = ttk.Frame(self.window)

    amount_label = ttk.Label(amount_frame, text="Amount:")
    amount_label.grid(row=0, column=0, padx=5, pady=5, sticky="e")

    self.amount = tk.StringVar()
    amount_entry = ttk.Entry(amount_frame, textvariable=self.amount)
    amount_entry.grid(row=0, column=1, padx=5, pady=5)

    amount_frame.pack()

    # Convert button
    convert_button = ttk.Button(self.window, text="Convert", command=self.convert)
    convert_button.pack(pady=10)

    # Result label
    self.result_var = tk.StringVar()
    self.result_var.set("")
    result_label = ttk.Label(self.window, textvariable=self.result_var)
    result_label.pack()

There‘s a lot going on here, so let‘s break it down:

  • We create a Frame widget called currency_frame to hold the currency selection dropdowns. Frames are invisible containers used to group and organize other widgets.

  • Inside currency_frame, we add two Label widgets for "From:" and "To:", and two Combobox widgets to select the currencies. Comboboxes are combination widgets that let users either type a value or select from a list of options.

  • The textvariable option ties each Combobox to a StringVar instance. This allows us to easily retrieve the selected currency later.

  • We populate the Comboboxes with a list of popular currencies using the values option. You can customize this list as desired. We also set default selections using the current method.

  • Another Frame called amount_frame holds a Label and Entry widget for entering the conversion amount. The Entry is tied to a StringVar so we can get its value.

  • A Button widget labeled "Convert" will trigger the actual currency conversion when clicked. Its command option specifies the method to call when the button is pressed (which we‘ll implement shortly).

  • Finally, a Label at the bottom will display the conversion result. It‘s tied to yet another StringVar that we‘ll update with the converted amount.

  • The pack geometry manager is used to automatically arrange the frames and widgets in the window.

If you run the code now, you should see the complete GUI with currency dropdowns, an amount entry, a convert button, and a result label. However, the conversion won‘t work yet because we haven‘t implemented the convert method triggered by the button.

Implementing currency conversion

The final step is to wire up the "Convert" button to perform the actual currency conversion using our CurrencyConverter class. Here‘s the code for the convert method:

def convert(self):
    amount = float(self.amount.get())
    from_currency = self.from_currency.get()
    to_currency = self.to_currency.get()

    converted_amount = self.converter.convert(from_currency, to_currency, amount)
    result = f"{amount} {from_currency} = {converted_amount:.2f} {to_currency}"
    self.result_var.set(result)

This method retrieves the user input from the amount, from_currency, and to_currency variables associated with the GUI widgets. It passes these values to the convert method of the CurrencyConverter instance to get the result.

Finally, it constructs a formatted string with the original and converted amounts and sets it as the value of result_var. This automatically updates the result label in the GUI.

With that, our currency converter application is complete! Run main.py and you should be able to select currencies, enter an amount, and click "Convert" to see the result.

Ideas for improvement

While our application is functional, there are many ways you could enhance it:

  • Add error handling for invalid inputs, such as non-numeric amounts or unsupported currencies.
  • Automatically update the exchange rates on a regular basis, or add a "Refresh Rates" button.
  • Allow the user to swap the "from" and "to" currencies.
  • Add a drop-down menu to select a different exchange rate provider.
  • Show a history of past conversions.
  • Improve the visual design with custom styles and layouts.

The possibilities are endless! Use this project as a starting point to explore more advanced GUI programming with Python and Tkinter.

In conclusion

In this tutorial, we‘ve seen how to build a complete GUI application with Python and Tkinter. You‘ve learned how to:

  • Structure a Tkinter application with classes and methods
  • Create and arrange GUI widgets like frames, labels, buttons, and dropdowns
  • Retrieve user input from entry fields and dropdowns
  • Trigger actions with button clicks
  • Integrate a GUI with an external API or library

Most importantly, you‘ve gained hands-on experience with the core concepts of GUI programming. With practice and experimentation, you‘ll be able to create intuitive, feature-rich desktop applications entirely in Python.

The real power of GUIs is that they allow you to make your code accessible to a wider audience. Not everyone can or wants to interact with a command line, but most people know how to use visual interfaces. By providing a GUI for your Python programs and scripts, you open them up to whole new groups of potential users.

In a world increasingly dominated by web and mobile apps, it‘s easy to forget about the value of traditional desktop software. But for many tasks – especially in business, science, and education – nothing beats a well-crafted native application. With Python and Tkinter, you have all the tools you need to build professional, cross-platform GUI apps quickly and easily.

So keep exploring, keep building, and most of all, keep sharing your creations with the world!

Additional Resources

Want to learn more about building GUIs with Python and Tkinter? Check out these resources:

Similar Posts