Prerequisites
The currency converter project in python requires you to have basic knowledge of python programming and the pygame library.
tkinter – For User Interface (UI)
requests – to get url
To install the tkinter and requests library, type the following code in your terminal:
pip install tkinter
pip install requests
To get real-time exchange rates, we will use: https://api.exchangerate-api.com/v4/latest/USD
Here, we can see the data in JSON format, with the following details:
Base – USD: It means we have our base currency USD. which means to convert any currency we have to first convert it to USD then from USD, we will convert it in whichever currency we want.
Date and time: It shows the last updated date and time.
Rates: It is the exchange rate of currencies with base currency USD.
For this project based on Python, we are using the tkinter and requests library. So we need to import the library.
3.1. Let’s create the constructor of class.
import requests
from tkinter import *
import tkinter as tk
from tkinter import ttk
requests.get(url) load the page in our python program and then .json() will convert the page into the json file. We store it in a data variable.
3.2. Convert() method:
def convert(self, from_currency, to_currency, amount):
initial_amount = amount
#first convert it into USD if it is not in USD.
# because our base currency is USD
if from_currency != 'USD' :
amount = amount / self.currencies[from_currency]
# limiting the precision to 4 decimal places
amount = round(amount * self.currencies[to_currency], 4)
return amount
This method takes following arguments:
From_currency: currency from which you want to convert.
to _currency: currency in which you want to convert.
Amount: how much amount you want to convert.
And returns the converted amount.
Example:
url = 'https://api.exchangerate-api.com/v4/latest/USD'
converter = RealTimeCurrencyConverter(url)
print(converter.convert('INR','USD',100))
To Create UI we will create a class CurrencyConverterUI
Converter: Currency Converter object which we will use to convert currencies. Above code will create a Frame.
Let’s Create the Converter
NOTE: This Code part of __init__ method.
First, we will create the Converter. Second, Create the UI for Converter
if __name__ == '__main__':
url = 'https://api.exchangerate-api.com/v4/latest/USD'
converter = RealTimeCurrencyConverter(url)
App(converter)
mainloop()