In software development, knowing how to build UIs (user interfaces) is really important. Ever wanted to make a UI for a project using a simple, high-level language like Python? The Tkinter module helps us do exactly that. Ever wanted to check the value of the currencies of different countries when compared to the currency of your own country? That can be done with another module called forex-python. In this tutorial, we will combine the forex-python module with the tkinter module to make a Currency Converter with a simple, minimalistic UI.
How the process will work.
Here's is how the program will work and in what order it will do so based on the user's input.
•Selecting Currencies:- First the user has to input both the input and output Currencies from the list provided by us.
•Selecting Amount:- Then the user has to select the amount to be converted into the output Currency.
•Clicking Convert:- After the convert button is clicked the entire script will fire up instantly.
Here I have provided a flowchart on how the script will work. The flowchart is explained below
This flowchart shows us the general idea the script should follow, whenever you are going to make a project it can be smart to make a flowchart on the general process of the script to get an idea for what you want to do. In this flowchart we can see that after the user clicks the concert button, we want our script to first check for both currencies aswell amount. Then we want our script to check for valid inputs in which we want the amount to be not negative so, amount>0 and we should convert the amount to str data type to avoid miscalculations. If these inputs are invalid we obviously want the script to reject these inputs and go back to the beginning. Next we should try to get live rates from forex-python if not possible then the script should give an error and go back the beginning aswell. Lastly if all checkpoints have been passed we want to give the result (obviously).
Now with the entire process in mind here is my code broken into smaller blocks of code with what each block does and why it's used. In a step-by-step manner.
Step-1 :- Importing the modules
import tkinter as tk
from tkinter import messagebox
from tkinter import ttk
Tkinter :- As discussed above tkinter is used for UI making.
Messagebox:- Just a subset of tkinter used to display a message in box in our case the result.
Ttk:- Used for making the widgets
Step 2:- Trying to import forex-python API
Now the reason we try to import the api is because we want the script to generate an error but if we just import it and the api is not available then the script would immediately crash for the user instead of a neat error box showed to the user.
# Requires installing the external library via terminal: pip install forex-python
try:
from forex_python.converter import CurrencyRates
currency_client = CurrencyRates()
# To print an error message if forex-python is not installed.
except ImportError:
print("Please install forex-python using pip install forex-python")
currency_client = None
Now if you are new to programming you might think why not just use if/else commands, well the reason we use try and excepts is primarily because try and except commands help us handle errors way better. Say if we used if/else commands it will look something like this
import importlib.util
# Check if the 'forex_python' module can be found in the system
if importlib.util.find_spec("forex_python") is not None:
from forex_python.converter import CurrencyRates
currency_client = CurrencyRates()
else:
print("Please install forex-python using pip install forex-python")
currency_client = None
Notice this is longer then before that is because the program wouldn't work with just replacing them, this block is longer and technically works but is still far inferior due to these reasons
•As you have probably noticed it's quite big longer because of an extra library
•If statement checks for the forex-python module twice while try command needs to check or 'try' to check it only once making it more efficient.
The rest of the code is quite self explanatory but here is what it does anyways
•First we try to get currency rates from forex python
•If the program doesn't get the currency rates the except part triggers which just generates an error which in this case is to simply print the following "Please install forex-python using pip install forex-python". Then it just sets currency client to none so the rest of the application doesn't crash.
Step 3 List of currencies supported.
Currencies = [
"USD",
"EUR",
"GBP",
"CAD",
"AUD",
"NZD",
"CHF",
"BRL",
"MXN",
"ZAR",
"TRY",
"RUB",
"SEK",
"NOK",
"DKK",
"INR",
"JPY",
"CNY",
"HKD",
"SGD",
"KRW",
"THB",
"PHP",
"IDR",
"MYR",
"ILS",
"PLN",
"CZK",
"HUF",
"RON",
"HRK",
"ISK",
] # List of currencies that are supported by forex-python
Now we just enter the currencies we want to use into a list. You can change the variable name and add or remove currencies (make sure to only the add currencies are supported by forex-python)
Step 4:- Changing the text on the buttons
# Function to change the text on the input currency button to the selected currency.
def set_input_choice(item, button_widget):
button_widget.config(text=item)
# To show a message box containing the text "you selected item" where item is the selected currency
messagebox.showinfo("Selection", f"You selected: {item}")
This block of the script is responsible for changing the text on the input and output currency buttons to the name of the selected currency. We start by defining the function then just change the text to the {item} which is the selected currency. Now why we do this is to easily check if a currency has been chosen, if yes, then which currency has been chosen. It's is easiesr to get the text on a menubutton then to get the value of a menubutton.
Step 5 To get the input currencies
# Function to get what the input that the user has given for amount and currencies are.
def click():
from_currency = Input_Currency.cget("text")
to_currency = Output_Currency.cget("text")
user_input = Entry_amount.get()
We will of course want to get the currencies the user has selected once they press the "convert" button. So we define a function as click() which just sets the from currency equal to the text that is displayed on the input_currency button which we will implement later. We do the same for the output_currency button. We also get the input for the amount using entry_amount.get().
(Note:- If you are having trouble understanding this I suggest you skip these steps for now and design the UI with the instructions on step 7 then comeback as it may be better for you to see the UI and the label names first in order to understand the script part to the UI.)
Step 6 To shows errors and give result.
# To check if the currencies have been selected if not then to display a selection error.
if (
from_currency == "Choose Input Currency"
or to_currency == "Choose Output Currency"
):
messagebox.showerror(
"Selection Error", "Please select both currencies first."
)
return
# To check that the input amount is of the float datatype if not then display an invalid amount error.
try:
amount = float(user_input)
except ValueError:
messagebox.showerror("Invalid Input", "Please enter a valid amount")
return
# To check whether the input amount is greater than zero display an error invalid amount otherwise.
if amount <= 0:
messagebox.showerror("Invalid Input", "Enter a number greater than zero")
return
# To try to convert the currencies using live rates if live rates aren't available then display a connection error.
try:
result = currency_client.convert(from_currency, to_currency, amount)
messagebox.showinfo(
"Conversion Result",
f"{amount} {from_currency} = {result} {to_currency}",
)
except Exception:
messagebox.showerror(
"Connection Error",
"Couldn't get internet access to fetch live rates",
)
# Function to show the user that they have 'selected' the selected currency.
def select_currency(item):
messagebox.showinfo("Selection", f"You selected: {item}")
This is the last part of the script and is responsible for giving the errors and the result. Here's is what this script does line by line
•First we check if the text on the menubutton has been changed from the default text. If the text remains the same then we display an error.
#To check if the currencies have been selected if not then to display a selection error.
if (
from_currency == "Choose Input Currency"
or to_currency == "Choose Output Currency"
):
messagebox.showerror(
"Selection Error", "Please select both currencies first."
)
return
•Then we check whether the input amount is a float datatype or and we subsequently also check if the amount is greater than zero a.k.a. , positive. And we display an error if otherwise for this we use this miniblock of code
# To check that the input amount is of the float datatype if not then display an invalid amount error.
try:
amount = float(user_input)
except ValueError:
messagebox.showerror("Invalid Input", "Please enter a valid amount")
return
# To check whether the input amount is greater than zero display an error invalid amount otherwise.
if amount <= 0:
messagebox.showerror("Invalid Input", "Enter a number greater than zero")
return
• Now that we have dealt with all the possible invalid amounts we want to convert the currencies (obviously) for that we have used this part of the code
# To try to convert the currencies using live rates if live rates aren't available then display a connection error.
try:
result = currency_client.convert(from_currency, to_currency, amount)
messagebox.showinfo(
"Conversion Result",
f"{amount} {from_currency} = {result} {to_currency}",
)
except Exception:
messagebox.showerror(
"Connection Error",
"Couldn't get internet access to fetch live rates",
)
We use an inbuilt function on forex-python which is the currency_client.convert()
This command converts the currencies with respect to the amount. We have trapped the result in the "result" variable for ease and then for convenience of the user we ideally also want to show the conversion taking place in a separate message box. We follow all that up with the exception part which just addresses that if the result passed through the previous checkpoints but failed this one the program just couldn't get internet access. We show this error in a separate error box like the previous ones.
Now finally we tell the user they have selected a currency and exactly which currency they chose through a message box using the following code
# Function to show the user that they have 'selected' the selected currency.
def select_currency(item):
messagebox.showinfo("Selection", f"You selected: {item}")
Step 7 Making the UI
root.geometry("300x350") # Size of the window
root.config(background="#000000") # Background colour in hex code in this case black
root.title("Currency Converter") # Title of the window
label = tk.Label(
root,
text="Currency converter",
font=("Arial", 20, "bold"),
fg="#FFFFFF",
bg="#000000",
) # To create a label with text "currency converter" with background and foreground colour with font size and text format in this case the text is bolded.
label.pack(pady=10) # To add padding to the y axis of the label.
Input_Currency = tk.Menubutton(
root, text="Choose Input Currency", bd=10, bg="#FFFFFF"
)
Input_Currency.pack() # To place a menu button with text, border and background color.
dropdown_menu = tk.Menu(Input_Currency, tearoff=0)
for currency in Currencies:
dropdown_menu.add_command(
label=currency,
command=lambda c=currency: set_input_choice(c, Input_Currency),
)
Input_Currency["menu"] = dropdown_menu
# To create and connect the menu with a list of the currencies to the menu button.
Entry_amount = tk.Entry(root, font=("Comic Sans MS", 15), bd=3, bg="#FFFFFF")
Entry_amount.insert(0, "100")
Entry_amount.place(x=150, y=140, anchor="center")
# To put an entry field with a default value of 100.
Output_Currency = tk.Menubutton(
root, text="Choose Output Currency", bd=10, bg="#FFFFFF"
)
Output_Currency.place(x=150, y=225, anchor="s")
# New menubutton for the output currency.
dropdown_menu2 = tk.Menu(Output_Currency, tearoff=0)
for currency in Currencies:
dropdown_menu2.add_command(
label=currency,
command=lambda c=currency: set_output_choice(c, Output_Currency),
)
Output_Currency["menu"] = dropdown_menu2
# To create and connect a new menu with the output currency button the list of currencies is the same in both menus.
Convert = tk.Button(root, text="Convert", command=click, padx=20, bd=10)
Convert.place(x=150, y=320, anchor="sw")
# To add a button which when clicked triggers the click function which is defined above from line 37 till line 75
root.mainloop() # To loop the window so that the GUI lasts until the user closes it.
Now here is what each command does
•root.geometry, root.title, root.config To change the size, title and settings like background colour of the window respectively.
•label To display text
•menubutton To create a button with an attachable menu for the possible values for the button.
•.pack and .place to place the widget pack just places it at the default point, while place has a coordinate system for you to choose from.
•tk.menu just the menu to be attached to the menubutton.
•tk.entry to make a box that accepts entry via typing
•tk.button to make a button with a function. If notice then only when the convert button is pressed is when the click() function is triggered and if you recall then the entire logic part of the script comes in the click function.
•root.mainloop() To make the window appear after the program is ran.
(Note:- you can customise this part as much as you want)
Congratulations
You have just learnt to make a
Currency converter using your now found knowledge of being able to understand both forex-python and tkinter modules. This is a very basic but an important project in order to understand these modules. Completing this project you have gained an understanding of:-
•tkinter
•forex-python
•UI making as a whole
•try and except commands
Note:- If you are having trouble using forex-python then you may consider waiting to switch to currency_converter library just replace them there won't be much of a change.

Top comments (0)