Image

Python GUIs: Building a Currency Converter Application using Tkinter — Convert between currencies wi

In this tutorial, you'll create acurrency converterapplication with Python and Tkinter. The app will allow the users to select the source currency, choose the target currency, and input the amount to convert. The application will use real-time exchange rates to convert from the source to target currency, providing accurate and up-to-date conversions.

FIXME: Add the demo video here...Currency converter demo

Through this project you'll gain hands-on experience working with Tkinter's GUI elements, handling user input, and interacting with an external API. By the end of the tutorial, you'll have a functional currency converter app and have learnt practical skills you can apply to your own Python & Tkinter projects.

Setting Up the Environment

We'll start by setting up a working environment for the project. We are using Tkinter for this project, which is included by default in most Python installations, so we don't need to install that.

If you're on Linux you may need to install it. See theLinux Tkinter installation instructions.

We'll also be using therequestslibrary to make HTTP requests to theExchange Rate APIwhich we can install from PyPi usingpip. We also want to create a folder to hold our project files including our Python script and images.

Below are the instructions to create a folder for our project calledcurrency_converter, set up a virtual environment, activate it and installrequestsinto that environment.

We will use the free Exchange Rate API to access real-time exchange rate data. It offers various endpoints that allow users to retrieve exchange rate information for different currency pairs, convert currency amounts from one currency to another, and perform other related operations. You'll have to sign up on the API page to be able to run the app.

Setting Up the Project Structure

Now that we've created the virtual environment and installed the required third-party libraries, we can set up the project structure.

Add a folder namedimagesto the root of your project.

Theimages/subfolder is where we will place the app's logo. Our application code will go in the root folder, namedcurrency_converter.py.

Getting Started with our Application

Now we have the project folder setup and requirements installed, we can start building our app. Create a new file calledcurrency_converter.pyat the root of the project folder and open this in your editor.

We'll start by adding the imports we need for our project, and building a basic window which will hold our application UI.

In the above code, we import theosandsysmodules from the Python standard library. Then, we import thetkinterpackage astk. This shorthand is typically used with Tkinter to save repeatedly typing the full name. We also import thetkinter.ttkpackage which gives us access to Tkinter's themed widgets, which looker nicer than the defaults. We also import Tkinter'smessageboxmodule for creating pop up dialogs. Finally, we import therequestslibrary to make HTTP requests to the API so that we can get up-to-date exchange rates and convert currencies.

We start by creating the application's root window, which in Tkinter also works as the application container. To do this we create a class calledCurrencyConverterApp, which inherits from thetk.Tkclass. On this class we add a custom__init__()method, which is called to initialize the object, where we set up the window's attributes.

To set the window's width, height, and position, we use thegeometry()method. For the window's title, we usetitle(). Finally, we useresizable()with thewidthandheightset to 0 to make the window unresizable.

With the main window class created, we then add the code to instantiate the class -- creating an instance of theCurrencyConverterApp-- and start up the main loop for the application. Themain loopis the event loop which handles user input events from the keyboard and mouse and passes them to the widgets.

When you run this code, you see the following window on your screen:

Currency converter's main window
Currency converter's main window

Currency converter's main window

There's not much to see for now: our currency converter doesn't have a functional GUI. It's just a plain window with an appropriate title and size.

Now let's create the app's GUI.

Creating the Currency Converter's GUI

To create the app's GUI, let's begin adding the widgets to the main window. We will add the following widgets:

  • The app's logo
  • Two labels and two associated combo boxes for selecting the source and target currency
  • A label for the amount to convert and an associated entry field
  • A label for displaying the conversion results
  • A button to run the conversion

First lets add the logo to our application.

We'll be including small snippets of the code as we build it. But the full code is shown below, to make sure you don't get mixed up.

In this code snippet, we first createbuild_gui()method to define all the widgets we need in our GUI. Inside the method, we load an image using thetk.PhotoImage()class.

Then, we create a label to display the image using thettk.Label()class, which takesselfandimageas arguments. Finally, we position the label in the main window using thepack()method, which is a geometry manager in Tkinter.

To use thebuild_gui()method, we need to call it. To do this, add the call toself.build_gui()to the end of the__init__()method. That gives us the following code.

Go ahead and run the app. You'll get an output like the following:

Currency converter window with logo
Currency converter window with logo

Currency converter window with logo

Now we can see something! We'll continue adding widgets to build up our UI.First, we will create a frame to position the widgets. Below the logo code we added in to thebuild_gui()method, add a frame:

Here, we create a frame using thetk.Frameclass. It takesselfas an argument because the current window is the frame's parent. To position the frame inside the main window, we use thepack()method.

With the frame in place, we can add some more widgets. Below is the code for populating the frame:

In this code, we create two labels using thettk.Label()class. We position them using thegrid()method. Then, we create the two combo boxes using thettk.Combobox()class, and position them both in the frame using thegrid()method again.

Note that we've positioned the labels in the first row of the frame while the combo boxes are in the second row. The GUI now will look something like this:

Currency converter's GUI
Currency converter's GUI

Currency converter's GUI

Great! Your app's GUI now has the widgets for selecting the source and target currencies. Let's now add the last four widgets. Below is the code for this:

In this code snippet, we add two labels using thettk.Label()class as usual. Then, we create the entry field using thettk.Entry()class. Next, we add theConvertbutton using thettk.Button()class. All these widgets must go inside the frame object.

Note that we've positioned theamount_labeland theamount_entryusing thegrid()method. In contrast, we've used thepack()method to place theresult_labelandconvert_button.

The complete current code is shown below.

Run this and you'll see the following window.

Currency converter's GUI
Currency converter's GUI

Currency converter's GUI

This is looking good now. The app's GUI is functionally complete. Even though you can't see the label showing the conversion result, this label is there and will be visible once we add something to it.

Implementing the Convert Currency Functionality

As mentioned, we will be using the Exchange Rate API to get our live currency data. To request data from the the API we need an API key. You can get one by signing up andcreating an account. This is free if you only need daily rates (fine for our app).

Exchange Rate API Sign-up Page
Exchange Rate API Sign-up Page

Exchange Rate API Sign-up Page

If you accept the terms, you will receive your API key via the email address you provided, or you can go to thedashboard, where you will see your API key as follows:

Exchange Rate API Key
Exchange Rate API Key

Exchange Rate API Key

Now that we have the API key, let's implement the currency conversion functionality. First, we will add the API key as an environment variable.

On Windows, open the terminal as an administrator and run the command below. Note that you must replace the "your_api_key" part with the actual API key:

Now, get back to your code editor. Below the imports, paste the following code:

Here, we retrieve the API key from the environment variable (that we just set) using theos.getenv()function. Using anifstatement, we check whether the key was set. If not, we issue an error message and terminate the app's execution using thesys.exit()function. Then, we set up the URL to get the latest currencies.

Run the code now -- in the same shell where you set the environment variable. If you see the error dialog then you know that the environment variable hasnotbeen set -- check the instructions again, and make sure the variable is set correctly in the shell where you are running the code. If you see the application as normal, then everything is good!

The error shown when API_KEY is not set correctly in the environment
The error shown when API_KEY is not set correctly in the environment

The error shown when API_KEY is not set correctly in the environment.

Interacting with the API

Now we have theAPI_KEYset up correctly we move on to interacting with the API itself. To do this we will create a method for getting all the currencies. Let's call itget_currencies(). Below thebuild_gui()method, add this new method:

The method above sends a GET request to the given URL. We convert the received JSON response to Python objects using thejson()method. Finally, we convert the conversion rates that come in the response to a Pythonlist.

We can populate the two combo boxes using theget_currencies()method. Add the following code to the bottom of thebuild_guimethod.

This calls theget_currenciesmethod to get the available currencies, and then populates the two combo boxes with the returned list.

If you run the application now, you'll see that the combo-boxes now contain the currencies returned from the API. Note that we're setting the default item to USD, which is the first currency in the list.

Populating the *From* Currency Combo Box
Populating the *From* Currency Combo Box

Populating theFromcurrency combo box

Populating the *To* Currency Combo Box
Populating the *To* Currency Combo Box

Populating theTocurrency combo box

Handling the Currency Conversion

The final step is to implement the actual currency conversion, using the values returned from the API. To do this we will create a method to handle this. Add new method calledconvert()to the bottom of ourCurrencyConverterAppclass.

In the first three lines, we get input data from thefrom_comboandto_combocombo boxes and theamount_entryfield using theget()method of each widget. Thefrom_combocombo box data is namedsrc, theto_combocombo box data is nameddest, and theamount_entryfield data is namedamount.

To get the conversion between currencies, we make a GET request to the API using a URL constructed using the input data. The result returned from the API is again in JSON format, which we convert to a Python dictionary by calling.json(). We take the"conversion_result"from the response and use this to update the result label with the conversion result.

The final step is to hook ourconvert()method up to a button so we can trigger it. To do this, we will add thecommandargument to the button's definition. The value for this argument will be assigned theconvertmethod object without the parentheses.

Here's how the button code will look after the update:

This code binds the button to theconvert()method. Now, when you click theConvertbutton, this method will run.

That's it! With these final touches, your currency converter application is complete. The full final code is shown below.

Run the final code and you will be able to convert amounts between any of the supported currencies. For example, select USD and EUR in thefromandtocombo boxes and enter a conversion amount of 100. The application will call the API and update the label with the result of the conversion, like follows:

Running currency converter app
Running currency converter app

Running currency converter app

Conclusion

Well done! You've built a functional currency converter application with Python & Tkinter. You've learnt the basics of building up a UI using Tkinter's widgets and layouts, how to use APIs to fill widgets with values and perform operations in response to user input.

If you want to take it further, think about some ways that you could improve the usability or extend the functionality of this application:

  • Do you have some conversions you do regularly? Add a way to quickly apply "favorite" currency conversions to the UI.
  • Add buttons to set standard amounts (10, 100, 1000) for conversion.
  • Use multiple API requests to show historic values (1 day ago, 1 week ago, 1 year ago) using thehistoric data API.

See if you can add these yourself! If you want to go further with Tkinter, take a look at ourcomplete TKinter tutorial.

https://www.pythonguis.com/examples/currency-converter-tkinter/