Movatterモバイル変換


[0]ホーム

URL:


How to Build a GUI Currency Converter using Tkinter in Python

Learn how to build a GUI currency converter using ExchangeRate API and Tkinter library in Python.
  · 13 min read · Updated aug 2022 ·Application Programming Interfaces ·Finance ·GUI Programming

Welcome! Meet ourPython Code Assistant, your new coding buddy. Why wait? Start exploring now!

Tkinter is one of those great built-in Python libraries that has been around for a long time; it is used to create snazzy graphical user interfaces (GUIs) for desktop applications. This article will teach you to build a currency converter application using the Tkinter library and ExchangeRate API.

If you wish to use another source of data, then checkthis tutorial, where we used five different sources for currency conversion, including Fixer API, Yahoo Finance, and more.

The ExchangeRate API is a real-time currency API that is both free and pro, it supports currency conversion rates for 161 currencies, and for a freemium account, you are required to make 250 requests per month, so using a free account will save the day for us.

At the end of this article, we are going to build an application that looks as follows:

Currency converter

Here is the table of contents:

Setting up the Project

First things first, let us set up the project. We will start by creating the virtual environment and then installing the Pythonrequests library.

Create a folder namedcurrencyconverter andcd into the folder:

$ mkdir currencyconverter $ cd currencyconverter

We will create the virtual environment in this folder and name itenv or any name of your choice:

$ python -m venv env

Activate the virtual environment, on Windows:

$ .\env\Scripts\activate.bat

On Linux/macOS:

$ source env/bin/activate

Now that the virtual environment is activated, let's install therequests library:

$ pip install requests

Designing the Graphical User Interface (GUI)

In this section, we will start designing the GUI for the application from the ground up. First of all, create a file namedcurrency_converter.py this is not a convention; you can name it whatever you want:

Designing the graphical user interface(GUI)

We will start by creating the main window of the application. Open the file and paste this code:

# importing everything from tkinterfrom tkinter import *# importing ttk widgets from tkinterfrom tkinter import ttk# creating the main windowwindow = Tk()# this gives the window the width(310), height(320) and the position(center)window.geometry('310x340+500+200')# this is the title for the windowwindow.title('Currency Converter')# this will make the window not resizable, since height and width is FALSEwindow.resizable(height=FALSE, width=FALSE)# this runs the window infinitely until it is closedwindow.mainloop()

In the above code, we are creating the main window using theTk() function that comes with Tkinter. We then define the dimensions of the window with thegeometry() function. To give the window a title, we are using thetitle() function.

We also use theresizable() function with its attributes set toFALSE to make the window non-resizable. Finally, themainloop() function will keep the app's window open until the user closes it.

If you run this program, you will get this output:

Designing the graphical user interface(GUI)

Now let us create two frames, the top frame and the button frame. The top frame will contain the text"Currency Converter" and it should look like this:

Currency converter

Just after this line of code:

window.resizable(height=FALSE, width=FALSE)

Paste these lines of code:

# colors for the applicationprimary = '#081F4D'secondary = '#0083FF'white = '#FFFFFF'# the top frametop_frame = Frame(window, bg=primary, width=300, height=80)top_frame.grid(row=0, column=0)# label for the text Currency Convertername_label = Label(top_frame, text='Currency Converter', bg=primary, fg=white, pady=30, padx=24, justify=CENTER, font=('Poppins 20 bold'))name_label.grid(row=0, column=0)

We added some colors and created the top frame containing the label. The top frame must be placed inside the main window that we have just created; the frame is taking three other attributes,bg,width, andheight.

The output of this code is this:

Let us now create the bottom frame; this frame will contain widgets likelabels,comboboxes,entry, and abutton. It will look as follows

Below thename_label paste this code:

# the top frametop_frame = Frame(window, bg=primary, width=300, height=80)top_frame.grid(row=0, column=0)# label for the text Currency Convertername_label = Label(top_frame, text='Currency Converter', bg=primary, fg=white, pady=30, padx=24, justify=CENTER, font=('Poppins 20 bold'))name_label.grid(row=0, column=0)# the bottom framebottom_frame = Frame(window, width=300, height=250)bottom_frame.grid(row=1, column=0)# widgets inside the bottom framefrom_currency_label = Label(bottom_frame, text='FROM:', font=('Poppins 10 bold'), justify=LEFT)from_currency_label.place(x=5, y=10)to_currency_label = Label(bottom_frame, text='TO:', font=('Poppins 10 bold'), justify=RIGHT)to_currency_label.place(x=160, y=10)# this is the combobox for holding from_currenciesfrom_currency_combo = ttk.Combobox(bottom_frame, width=14, font=('Poppins 10 bold'))from_currency_combo.place(x=5, y=30)# this is the combobox for holding to_currenciesto_currency_combo = ttk.Combobox(bottom_frame, width=14, font=('Poppins 10 bold'))to_currency_combo.place(x=160, y=30)# the label for AMOUNTamount_label = Label(bottom_frame, text='AMOUNT:', font=('Poppins 10 bold'))amount_label.place(x=5, y=55)# entry for amountamount_entry = Entry(bottom_frame, width=25, font=('Poppins 15 bold'))amount_entry.place(x=5, y=80)# an empty label for displaying the resultresult_label = Label(bottom_frame, text='', font=('Poppins 10 bold'))result_label.place(x=5, y=115)# an empty label for displaying the timetime_label = Label(bottom_frame, text='', font=('Poppins 10 bold'))time_label.place(x=5, y=135)# the clickable button for converting the currencyconvert_button = Button(bottom_frame, text="CONVERT", bg=secondary, fg=white, font=('Poppins 10 bold'))convert_button.place(x=5, y=165)

We are creating a bottom frame; just like the top frame, we will place the bottom frame inside the main window. Inside this frame, we will place the remaining widgets, the two labels, the two combo boxes, the entry, and the button.

Running the code, you will get this output:

Congratulations on successfully designing the graphical user interface of the application!

Getting the API Key for the ExchangeRate API

The ExchangeRate API requires us to have an API key that will enable us to make successful requests to it. To get the API Key, go tothis URL and enter your email in the email field:

 Getting the API Key for the ExchangeRate API

Click theGet Free Key button, and you will be prompted to create an account. After providing your credentials, it will take you to this window:

Sign in to your email account and confirm your email address to activate your ExchangeRate API account. You will find the email in the promotions folder; if not, check the primary or spam folder.

If you have confirmed successfully, you will be taken to the ExchangeRate API dashboard, and in your dashboard, you will also find your personal secret API Key. For security reasons, this key is not to be shared.

In the dashboard, on the side navigation bar under Documentation, click theDocs Overview link:

Or visitthis URL.Here we will focus on two requests, standard and pair conversion:

TheStandard request will return the whole list of currencies that the API provides, and it takes this format:

https://v6.exchangerate-api.com/v6/YOUR-API-KEY/latest/USD

On the other hand, thePair Conversion request will convert two given currencies, and it takes this format:

https://v6.exchangerate-api.com/v6/YOUR-API-KEY/pair/EUR/GBP

Populating the Combo Boxes with Currencies

We have created the combo boxes, but they hold no values, so let's populate them with the currencies so that the user will select currencies from them. For this, we will use theStandard request to give us the list of currencies. Below your imports, paste these lines of code:

import requestsimport jsonAPI_KEY = "put your API key here"# the Standard request urlurl = f'https://v6.exchangerate-api.com/v6/{API_KEY}/latest/USD'# making the Standard request to the API and converting the request to jsonresponse = requests.get(f'{url}').json()# converting the currencies to dictionariescurrencies = dict(response['conversion_rates'])

Make sure to replace theAPI_KEY with your real API Key.

Scroll down to where you have defined the two combo boxes. The combo box takes an argument calledvalues and its data type must be a list. Now make the first combo box look like this:

from_currency_combo = ttk.Combobox(bottom_frame, values=list(currencies.keys()), width=14, font=('Poppins 10 bold'))

As you can notice, we have added thevalues argument to the combo box, and it is taking all the keys of the currencies dictionaryin the form of a list.

Testing this:

Let us also populate the second combo box:

to_currency_combo = ttk.Combobox(bottom_frame, values=list(currencies.keys()), width=14, font=('Poppins 10 bold'))

Result:

Implementing the Currency Conversion Functionality

Now that all the combo boxes are working, it is time we implement the convert currency functionality. All this will be done inside a function. Remember to do aPair Conversion; we use this URL:

https://v6.exchangerate-api.com/v6/YOUR-API-KEY/pair/EUR/GBP

Creating the function for converting the two pairs of currencies just above the:

window = Tk()

Paste the following code:

def convert_currency():    # getting currency from first combobox    source = from_currency_combo.get()    # getting currency from second combobox    destination = to_currency_combo.get()    # getting amound from amount_entry    amount = amount_entry.get()    # sending a request to the Pair Conversion url and converting it to json    result = requests.get(f'https://v6.exchangerate-api.com/v6/{API_KEY}/pair/{source}/{destination}/{amount}').json()    # getting the conversion result from response result    converted_result = result['conversion_result']    # formatting the results    formatted_result = f'{amount} {source} = {converted_result} {destination}'    # adding text to the empty result label    result_label.config(text=formatted_result)    # adding text to the empty time label    time_label.config(text='Last updated,' + result['time_last_update_utc'])

Theconvert_currency() function is getting currencies from the two combo boxes and the amount from the entry using theget() function. These values and the API key are passed to the API request. The result of the request is converted to JSON using thejson() function.

This function will be triggered when we click theConvert button, so we need to tell the button to trigger this function. In Tkinter, buttons take acommand argument with a function as a value, so we will make the button look like this:

convert_button = Button(bottom_frame, text="CONVERT", bg=secondary, fg=white, font=('Poppins 10 bold'), command=Convert_Currency)

Now the button knows what function to trigger after it is clicked, let us test this, run the program and fill the combo boxes with data (from EUR to USD) and enter an amount of 1000, click the button, and make sure you get the below output:

Catching Exceptions

The application runs successfully, but what if the user clicks theConvert button without filling the required fields? The answer is obvious, the application will throw an error, but the user will not see this error since it will occur in the backend.

So next, we need to improve the application's user experience; we will make it possible for the user to know what errors have occurred. In the file, under the imports section, paste this code:

# tkinter message box for displaying errorsfrom tkinter.messagebox import showerror

The code inside theconvert_currency() function will be inside a try/except block. The code wrapped inside thetry statement will run if there are no exceptions. Otherwise, the code inside theexcept statement will get executed:

def convert_currency():    # will execute the code when everything is ok    try:        # getting currency from first combobox        source = from_currency_combo.get()        # getting currency from second combobox        destination = to_currency_combo.get()        # getting amound from amount_entry        amount = amount_entry.get()        # sending a request to the Pair Conversion url and converting it to json        result = requests.get(f'https://v6.exchangerate-api.com/v6/{API_KEY}/pair/{source}/{destination}/{amount}').json()        # getting the conversion result from response result        converted_result = result['conversion_result']        # formatting the results        formatted_result = f'{amount} {source} = {converted_result} {destination}'        # adding text to the empty result label        result_label.config(text=formatted_result)        # adding text to the empty time label        time_label.config(text='Last updated,' + result['time_last_update_utc'])    # will catch all the errors that might occur     # ConnectionTimeOut, JSONDecodeError etc    except:        showerror(title='Error', message='An error occurred!!')

Rerun the application, but this time around, do not fill the required fields and click theConvert button. We will get this output:

Now the application can catch all the errors and display them to the user.

Conclusion

Congratulations on successfully building a currency converter GUI app. You can get the complete code for this applicationhere.

That's it for this tutorial! We hope you enjoyed this article on how to build a currency converter application using Python, Tkinter, and ExchangeRate API. We hope it helps you with your future Python projects.

Inthis tutorial, we have built five different currency converters using ExchangeRate API, Fixer API, Yahoo Finance, Xe, and X-RATES. Make sure to check it out and merge it with this GUI.

Learn also:How to Make a Calculator with Tkinter in Python.

Happy coding ♥

Save time and energy with ourPython Code Generator. Why start from scratch when you can generate? Give it a try!

View Full Code Switch My Framework
Sharing is caring!



Read Also


How to Make a Markdown Editor using Tkinter in Python
How to Make a File Explorer using Tkinter in Python
How to Make a Text Editor using Tkinter in Python

Comment panel

    Got a coding query or need some guidance before you comment? Check out thisPython Code Assistant for expert advice and handy tips. It's like having a coding tutor right in your fingertips!





    Ethical Hacking with Python EBook - Topic - Top


    Join 50,000+ Python Programmers & Enthusiasts like you!



    Tags


    New Tutorials

    Popular Tutorials


    Ethical Hacking with Python EBook - Topic - Bottom

    CodingFleet - Topic - Bottom






    Claim your Free Chapter!

    Download a Completely Free Ethical hacking with Python from Scratch Chapter.

    See how the book can help you build awesome hacking tools with Python!



    [8]ページ先頭

    ©2009-2025 Movatter.jp