Currency Converter Using Python - Themidom

Well, hello python programmers. This is Themidom, today in this post we will know how we can create a Currency Converter from scratch using python. And, remember it may not be beginner-friendly. If you know about classes constructor, then you are free to go. 


Overview

In this project we have used 4 python modules:
1) Tkinter - for UI
2) requests - for API 
3) re - for checking the character

So, you need to install requests - just run
pip install request 
or you can google it.

As, usual we will import the modules - 

 import requests  
 from tkinter import *  
 import tkinter as tk  
 from tkinter import ttk  
 from tkinter import messagebox  
 import re  
Now, we will make its interface - 

 class App(tk.Tk):  
   def __init__(self, converter):  
     tk.Tk.__init__(self)  
     self.title = 'Currency Converter'  
     self.config(bg='black')  
     self.currency_converter = converter  
     #self.configure(background = 'blue')  
     self.geometry("520x200")  
     self.resizable(0,0)  
     # Label  
     self.intro_label = Label(self, text = 'Welcome to Real Time Currency Convertor', bg='black', fg = 'blue', relief = tk.RAISED, borderwidth = 3)  
     self.intro_label.config(font = ('Courier',15,'bold'))  
     self.date_label = Label(self, text = f"1 Indian Rupee equals = {self.currency_converter.convert('INR','USD',1)} USD \n Date : {self.currency_converter.data['date']}", relief = tk.GROOVE, borderwidth = 5)  
     self.intro_label.place(x = 10 , y = 5)  
     self.date_label.place(x = 160, y= 50)  
     # Entry box  
     valid = (self.register(self.restrictNumberOnly), '%d', '%P')  
     self.amount_field = Entry(self,bd = 3, relief = tk.RIDGE,fg = 'red', bg = 'yellow', justify = tk.CENTER,validate='key', validatecommand=valid, font=('verdana',17,'bold'), width = 10,)  
     self.converted_amount_field_label = Label(self, text = '', fg = 'red', bg = 'yellow', relief = tk.RIDGE, justify = tk.CENTER, font=('verdana',17,'bold'), width = 10, borderwidth = 3)  
     # dropdown  
     self.from_currency_variable = StringVar(self)  
     self.from_currency_variable.set("INR") # default value  
     self.to_currency_variable = StringVar(self)  
     self.to_currency_variable.set("USD") # default value  
     font = ("Courier", 16, "bold")  
     self.option_add('*TCombobox*Listbox.font', font)  
     self.from_currency_dropdown = ttk.Combobox(self, textvariable=self.from_currency_variable,values=list(self.currency_converter.currencies.keys()), font = font, state = 'readonly', width = 12, justify = tk.CENTER)  
     self.to_currency_dropdown = ttk.Combobox(self, textvariable=self.to_currency_variable,values=list(self.currency_converter.currencies.keys()), font = font, state = 'readonly', width = 12, justify = tk.CENTER)  
     # placing  
     self.from_currency_dropdown.place(x = 30, y= 120)  
     self.amount_field.place(x = 36, y = 150)  
     self.to_currency_dropdown.place(x = 340, y= 120)  
     #self.converted_amount_field.place(x = 346, y = 150)  
     self.converted_amount_field_label.place(x = 346, y = 150)  
     # Convert button  
     self.convert_button = Button(self, text = "Convert", fg = "black", command = self.converted)   
     self.convert_button.config(font=('Courier', 10, 'bold'))  
     self.convert_button.place(x = 225, y = 135)  
     self.bind('<Return>', self.perform)  
Now We will add some logic:-


 class RealTimeCurrencyConverter():  
   def __init__(self,url):  
       self.data = requests.get(url).json()  
       self.currencies = self.data['rates']  
   def convert(self, from_currency, to_currency, amount):   
     initial_amount = amount   
     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  
Now, if we put it all together, and add make an API request using the requests module, then the full source code looks like this:

Full Code:


 import requests  
 from tkinter import *  
 import tkinter as tk  
 from tkinter import ttk  
 from tkinter import messagebox  
 import re  
 class RealTimeCurrencyConverter():  
   def __init__(self,url):  
       self.data = requests.get(url).json()  
       self.currencies = self.data['rates']  
   def convert(self, from_currency, to_currency, amount):   
     initial_amount = amount   
     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  
 class App(tk.Tk):  
   def __init__(self, converter):  
     tk.Tk.__init__(self)  
     self.title = 'Currency Converter'  
     self.config(bg='black')  
     self.currency_converter = converter  
     #self.configure(background = 'blue')  
     self.geometry("520x200")  
     self.resizable(0,0)  
     # Label  
     self.intro_label = Label(self, text = 'Welcome to Real Time Currency Convertor', bg='black', fg = 'blue', relief = tk.RAISED, borderwidth = 3)  
     self.intro_label.config(font = ('Courier',15,'bold'))  
     self.date_label = Label(self, text = f"1 Indian Rupee equals = {self.currency_converter.convert('INR','USD',1)} USD \n Date : {self.currency_converter.data['date']}", relief = tk.GROOVE, borderwidth = 5)  
     self.intro_label.place(x = 10 , y = 5)  
     self.date_label.place(x = 160, y= 50)  
     # Entry box  
     valid = (self.register(self.restrictNumberOnly), '%d', '%P')  
     self.amount_field = Entry(self,bd = 3, relief = tk.RIDGE,fg = 'red', bg = 'yellow', justify = tk.CENTER,validate='key', validatecommand=valid, font=('verdana',17,'bold'), width = 10,)  
     self.converted_amount_field_label = Label(self, text = '', fg = 'red', bg = 'yellow', relief = tk.RIDGE, justify = tk.CENTER, font=('verdana',17,'bold'), width = 10, borderwidth = 3)  
     # dropdown  
     self.from_currency_variable = StringVar(self)  
     self.from_currency_variable.set("INR") # default value  
     self.to_currency_variable = StringVar(self)  
     self.to_currency_variable.set("USD") # default value  
     font = ("Courier", 16, "bold")  
     self.option_add('*TCombobox*Listbox.font', font)  
     self.from_currency_dropdown = ttk.Combobox(self, textvariable=self.from_currency_variable,values=list(self.currency_converter.currencies.keys()), font = font, state = 'readonly', width = 12, justify = tk.CENTER)  
     self.to_currency_dropdown = ttk.Combobox(self, textvariable=self.to_currency_variable,values=list(self.currency_converter.currencies.keys()), font = font, state = 'readonly', width = 12, justify = tk.CENTER)  
     # placing  
     self.from_currency_dropdown.place(x = 30, y= 120)  
     self.amount_field.place(x = 36, y = 150)  
     self.to_currency_dropdown.place(x = 340, y= 120)  
     #self.converted_amount_field.place(x = 346, y = 150)  
     self.converted_amount_field_label.place(x = 346, y = 150)  
     # Convert button  
     self.convert_button = Button(self, text = "Convert", fg = "black", command = self.converted)   
     self.convert_button.config(font=('Courier', 10, 'bold'))  
     self.convert_button.place(x = 225, y = 135)  
     self.bind('<Return>', self.perform)  
   def converted(self):  
     amount = float(self.amount_field.get())  
     from_curr = self.from_currency_variable.get()  
     to_curr = self.to_currency_variable.get()  
     try:  
       converted_amount = self.currency_converter.convert(from_curr,to_curr,amount)  
       converted_amount = round(converted_amount, 2)  
       self.converted_amount_field_label.config(text = str(converted_amount))  
     except:  
       messagebox.showerror(self, "What the f man, See there is an error, try to fix it")  
   def perform(self, x):  
     amount = float(self.amount_field.get())  
     from_curr = self.from_currency_variable.get()  
     to_curr = self.to_currency_variable.get()  
     try:  
       converted_amount = self.currency_converter.convert(from_curr,to_curr,amount)  
       converted_amount = round(converted_amount, 2)  
       self.converted_amount_field_label.config(text = str(converted_amount))  
     except:  
       messagebox.showerror(self, "What the f man, See there is an error, try to fix it")  
   def restrictNumberOnly(self, action, string):  
     regex = re.compile(r"[0-9,]*?(\.)?[0-9,]*$")  
     result = regex.match(string)  
     return (string == "" or (string.count('.') <= 1 and result is not None))  
 if __name__ == '__main__':  
   url = 'https://api.exchangerate-api.com/v4/latest/USD'  
   converter = RealTimeCurrencyConverter(url)  
   App(converter)  
   mainloop()  
And we are done, now you need to save the whole source code into a file name of your choice, then just run and see, If you see this interface you got it right, my friend, if not just comment below.


Now, guess what, that's it for this post, thanks for reading the post see ya in the next.
                                    ---Themidom

1 Comments

If you have have any doubt please let me know

  1. Casino Roll
    Casino 바카라사이트추천 Roll. 썬 시티 Casino Roll. Casino Roll. 워커힐 카지노 The brand new online casino brings the exciting fun and excitement of Las Vegas to 비윈티비 your fingertips. Rake.com is powered 태평양 먹튀

    ReplyDelete
Previous Post Next Post

Ads

Ads