Wouldn’t it be great to know the value of your dollar (or any other currency) compared to another when planning that dream trip to Europe? Whether it’s figuring out the cost of a hotel, renting a car, or finally indulging in that delicious Italian pizza you’ve been craving, having a quick way to convert currencies would be super helpful.
In this article, we’ll create a Python application to help with currency conversion using Tkinter
for an elegant and user-friendly interface (GUI). Python is a beginner-friendly language with powerful libraries and APIs, making it perfect for building a variety of applications, including this one.
We’ll use an exchange rate API to fetch real-time currency exchange rates, learn how to handle user inputs and edge cases and build a simple, intuitive interface.
Install requests
library using pip:
pip install requests
The app will handle the below three tasks:
import requests
import tkinter as tk
from tkinter import ttk, messagebox
The requests
library will help us make HTTP requests to the currency conversion API
The get_exchange_rates
function retrieves real-time exchange rates. If the request is successful, it returns the conversion rates. Otherwise, it raises an error.
P.S: You can get the API_KEY from the Exchangerate-API website for free and it also has instructions on how to use their API.
def get_exchange_rates(api_key):
url = f"https://v6.exchangerate-api.com/v6/{api_key}/latest/USD"
response = requests.get(url)
if response.status_code == 200:
return response.json()['conversion_rates']
else:
raise Exception("Error getting the rates")
The convert_currency
function handles the actual conversion between two currencies. It first checks if both the from_currency
and the to_currency
are available in the rates
dictionary. If not, it will throw a ValueError
def convert_currency(amt, from_currency, to_currency, rates):
if from_currency not in rates or to_currency not in rates:
raise ValueError("currency code is incorrect")
converted_amt = amt * (rates[to_currency] / rates[from_currency])
return converted_amt
The perform_conversion
function gets the amount
and the from_currency
and to_currency
that the user enters in the GUI. It calls convert_currency
to calculate the actual converted_amount
. The result is displayed in result_label
which is a global variable. If it encounters any issues, ValueError
will be thrown (e.g., invalid input) and an error message will be shown to the user using messagebox.showerror
def perform_conversion():
try:
amt = float(amt_entry.get())
from_curr = from_currency_var.get()
to_curr = to_currency_var.get()
converted_amt = convert_currency(amt, from_curr, to_curr, rates)
result_label.config(text=f"{amt} {from_curr} is equal to {converted_amt:.2f} {to_curr}")
except ValueError as ve:
messagebox.showerror("User Input Error. Please check", str(ve))
except Exception as e:
messagebox.showerror("General Error", str(e))
The setup_gui
sets up the interactive user interface allowing users to enter values. We first initialize the root and then set its title. We then set up different components/widgets like - a field for the user to enter the amount
and dropdown options for selecting from_currency
and to_currency
, which will have default values "USD" and "EUR," respectively. These dropdown selectors are implemented using ttk.Combobox
, which provides a list of all the available currencies (this will ensure the user can’t enter an invalid currency code). Then we add a "Convert" button, which will be used to trigger the perform_conversion
function when clicked. The result_label
will display the conversion output(with a large font for readability). The Tkinter event loop is then finally started with root.mainloop()
, which will make the GUI remain responsive and interactive, waiting for any further actions from the user.
def setup_gui():
global result_label, amount_entry, from_currency_var, to_currency_var
root = tk.Tk()
root.title("Currency Converter")
tk.Label(root, text="Amount:").grid(row=0, column=0, padx=10, pady=10)
amount_entry = tk.Entry(root)
amount_entry.grid(row=0, column=1, padx=10, pady=10)
tk.Label(root, text="From Currency:").grid(row=1, column=0, padx=10, pady=10)
from_currency_var = tk.StringVar(value="USD")
from_currency_menu = ttk.Combobox(root, textvariable=from_currency_var, values=list(rates.keys()))
from_currency_menu.grid(row=1, column=1, padx=10, pady=10)
tk.Label(root, text="To Currency:").grid(row=2, column=0, padx=10, pady=10)
to_currency_var = tk.StringVar(value="EUR")
to_currency_menu = ttk.Combobox(root, textvariable=to_currency_var, values=list(rates.keys()))
to_currency_menu.grid(row=2, column=1, padx=10, pady=10)
convert_button = tk.Button(root, text="Convert", command=perform_conversion)
convert_button.grid(row=3, column=0, columnspan=2, pady=20)
result_label = tk.Label(root, text="", font=("Helvetica", 14))
result_label.grid(row=4, column=0, columnspan=2, pady=10)
root.mainloop()
The main
function is where we set the API key which will be passed to get_exchange_rates
function and using Exception
block any errors that we might encounter will be displayed to the user using the messagebox.showerror
method with details on what the error is.
Then finally we call the setup_gui
which will start the GUI:
def main():
global rates
api_key = "API_KEY" # use your actual key
try:
rates = get_exchange_rates(api_key)
except Exception as e:
messagebox.showerror("Error", f"An error occurred: {e}")
return 0
setup_gui()
if __name__ == "__main__":
main()
This tutorial demonstrated how to leverage APIs to fetch real-time data, handle user inputs, and build a responsive GUI using Python. You can extend this app with advanced features like historical exchange rates, additional currencies, or enhanced UI using PyQt. Hopefully, this inspires you to create more Python tools to simplify everyday tasks!