Python

Tkinter: GUI in Python

GUIs allow users to interact with the computer and are an important part of coding. This tutorial will learn how to use Tkinter to create a GUI, particularly a currency converter.

Install tkinter as follows:

pip install tk

Step 1: Creating The Window

The first thing we need to do is to create the window using the Tk() class. However, we start the window and keep it going using the mainloop() method. Please note that the window you created will not be visible without the mainloop() method! Remember that the mainloop() method must be placed at the end of the code; otherwise, the rest won’t work. The window.mainloop() and the Tk() together will create a blank and empty window. This window is our base.

Import tkinter as tk

# create the window
window = tk.Tk()

#Mainloop
window.mainloop()

Step 2: Give Window A Title

Next, let’s give this blank window a title using the title() method. The title() method takes a single argument – the title of the window. 

import tkinter as tk

window = tk.Tk()

# Give it a title
Header = window.title("Currency Converter")

window.mainloop()

Step 3: Create A Canvas

The Canvas widget is used to add designs. We now define the Canvas widget, which can take 13 arguments maximally. However, the most important arguments are the window we want to work with and the canvas’s height and width. In Tkinter, most things are packed, so the canvas is packed using the pack() method to work.

import tkinter as tk

window = tk.Tk()
Header = window.title("Currency Converter")
canvas = tk.Canvas(window, width=550, height=330)
canvas.pack()

window.mainloop()

Step 4: Adding Labels

Labels are basically just bits of texts that we add to the window.  In my case, I will add 3 labels – one label is the title, and the other two are instructions. The Label widget takes 2 arguments here – the window to place the text and the text to write in it. You can further customize it using config() to pass the font and the size of the text you just wrote.

We further create a canvas window object by using create_window(). Create_window() takes at most 6 arguments – the anchor, the height, the state, tags, width, and window (the widget used to make the canvas). We will only use anchor and window for create_windows(). So in my case, for the second label – label_search_bar – I want it positioned at x=150, y=120, and the window I will use is the Label that we created (canvas.create_window(150, 120, window=label_search_bar)).

import tkinter as tk

window = tk.Tk()
Header = window.title("Currency Converter")
canvas = tk.Canvas(window, width=550, height=330)
canvas.pack()

label = tk.Label(window, text="Kalyani's Currency Converter")
label.config(font=('helvetica', 14))
canvas.create_window(270, 75, window=label)

label_search_bar = tk.Label(window, text="From (ex: 500 USD):")
label.config(font=('helvetica', 14))
canvas.create_window(150, 120, window=label_search_bar)

label_convert_currency = tk.Label(window, text="To (ex: CAD):")
label.config(font=('helvetica', 14))
canvas.create_window(270, 120, window=label_convert_currency)

window.mainloop()

Step 5: Adding An Input Bar

An input bar is like a search bar; it’s a small box where you can input data or information. We use the Entry widget to create the input bar. The Entry widget takes at most 18 arguments. We will only use one of them – the parent window. We then place it, as usual, using canvas.create_window().

import tkinter as tk

window = tk.Tk()
Header = window.title("Currency Converter")
canvas = tk.Canvas(window, width=550, height=330)
canvas.pack()

label = tk.Label(window, text="Kalyani's Currency Converter")
label.config(font=('helvetica', 14))
canvas.create_window(270, 75, window=label)

label_search_bar = tk.Label(window, text="From (ex: 500 USD):")
label.config(font=('helvetica', 14))
canvas.create_window(150, 120, window=label_search_bar)

label_convert_currency = tk.Label(window, text="To (ex: CAD):")
label.config(font=('helvetica', 14))
canvas.create_window(270, 120, window=label_convert_currency)

search_bar = tk.Entry(window)
canvas.create_window(150, 150, height=30, width=100, window=search_bar)

convert_currency = tk.Entry(window)
canvas.create_window(270, 150, height=30, width=100, window=convert_currency)

window.mainloop()

Step 6: Adding A Button

In order to create a button, we need the button widget. This widget takes in a lot of arguments, amongst which are the text (the text to display on the button), the width, the height, the bg (the background color of the button), the fg (the foreground color of the button), the font and the command. Here, the most important part is the command! The command will define a function that will be activated when the button is clicked. In my case, I’ve called my function CurrencyConverter. To begin with, I will put “pass” in my function CurrencyConverter. (We, of course, locate the button using create_window).

import tkinter as tk

def CurrencyConverter():
    pass

window = tk.Tk()
Header = window.title("Currency Converter")
canvas = tk.Canvas(window, width=550, height=330)
canvas.pack()

label = tk.Label(window, text="Kalyani's Currency Converter")
label.config(font=('helvetica', 14))
canvas.create_window(270, 75, window=label)

label_search_bar = tk.Label(window, text="From (ex: 500 USD):")
label.config(font=('helvetica', 14))
canvas.create_window(150, 120, window=label_search_bar)

label_convert_currency = tk.Label(window, text="To (ex: CAD):")
label.config(font=('helvetica', 14))
canvas.create_window(270, 120, window=label_convert_currency)

search_bar = tk.Entry(window)
canvas.create_window(150, 150, height=30, width=100, window=search_bar)

convert_currency = tk.Entry(window)
canvas.create_window(270, 150, height=30, width=100, window=convert_currency)

button = tk.Button(
    window,
    text="Convert Currency",
    width=25,
    height=3,
    bg="white",
    fg="black",
    font=('helvetica', 9, 'bold'),
    command=CurrencyConverter
    )

canvas.create_window(275, 200, height=40,width=150, window=button)

window.mainloop()

Step 7: Writing The Command Function

Here, the command function will tell the program what to do when the user clicks on the button. In my case, I’d like it to:

  • Get the input values using the get() method.
  • Check the input values. I want a number and a currency in the first input bar, and in the second, I want a currency.
  • Convert the currency values using the CurrencyConverter module in python.
  • Chuck out the value
import tkinter as tk

def CurrencyConverter():

First, we will fetch what the user wrote in the input bars using the get() method and place it in initial_currency.

    initial_currency = search_bar.get()

Here, we expect two values (ex: 500 USD), so we then split it to turn it into an array.

array = initial_currency.split(" ")

We then say that if the length of that array is not 2, we want it to throw an error on the window screen. In my case, I will use the Label() widget to create the text to be displayed. That is to say, if the length of my array is not 2, then write “Please enter an amount and a currency type (ex: 500 USD)” on the screen. Place it using canvas.create_windows().

    if len(array) != 2:
        print_out = Label(window, text="Please enter an amount, and a currency type (ex: 500 USD)")
        canvas.create_window(250, 310, window=print_out)

We then want to fetch the values that were inputted. The amount is the first value in the array, and the currency type is the second value in the array.

    amount = int(array[0])
    currency = str(array[1]).upper()

Next, we need the currency type that the amount is being converted into (ex: 500 USD to CAD). I have defined a variable called to_currency to get the user’s input in the second input bar. Once again, we use the get() method to fetch the value.

to_currency = convert_currency.get()

Now, we need to tamper with what we just got.  The user inputted some stuff, and we just want the first value of what was inputted, so we split everything and pick out the first value using [0]. (I also turn everything to uppercase to avoid problems).

    array_to_currency = to_currency.split(" ")
    to_currency = str(array_to_currency[0])
    to_currency = to_currency.upper()

Now, we use a module from python called currency converter (pip install CurrencyConverter). We convert the currency and obtain an amount (here, I call this variable amount_converted).

    from currency_converter import CurrencyConverter
    c = CurrencyConverter()
    amount_converted = c.convert(amount, currency, to_currency)

Next, we need to print this out on the Window. As we know, we print out text using the Label widget. Since the amount_converted (the converted currency) is a float, we say:

    text_to_input = str(amount_converted) + " "+to_currency

    print_out_answer = Label(window, text=text_to_input)

    canvas.create_window(450, 150, window=print_out_answer)

The whole code would look like this:

from tkinter import *

def CurrencyConverter():
    # get the input in the search bar
    initial_currency = search_bar.get()

    # split it
    array = initial_currency.split(" ")

    if len(array) != 2:
        print_out = Label(window, text="Please enter an amount, and a currency type (ex: 500 USD)")
        canvas.create_window(250, 310, window=print_out)

    # get the "from" amount and the dollar amount
    amount = int(array[0])
    currency = str(array[1]).upper()

    # get the input in the currency convert to
    to_currency = convert_currency.get()
    array_to_currency = to_currency.split(" ")
    to_currency = str(array_to_currency[0])
    to_currency = to_currency.upper()

    # convert it
    from currency_converter import CurrencyConverter
    c = CurrencyConverter()
    amount_converted = c.convert(amount, currency, to_currency)

    # print out the answer
    text_to_input = str(amount_converted) + " "+to_currency
    print_out_answer = Label(window, text=text_to_input)
    canvas.create_window(450, 150, window=print_out_answer)

# create the window
window = Tk()

# create a canvas and pack it
canvas = Canvas(window, width=550, height=330, relief='raised')
canvas.pack()

# Give it a title
Header = window.title("Kalyani's Currency Converter")

# name of browser
label = Label(window, text="Kalyani's Currency Converter")
label.config(font=('helvetica', 14))
canvas.create_window(270, 75, window=label)

# Create a search bar
search_bar = Entry(window, justify=CENTER)
canvas.create_window(150, 150, height=30, width=100, window=search_bar)

# label the search bar
label_search_bar = Label(window, text="From (ex: 500 USD):")
label.config(font=('helvetica', 14))
canvas.create_window(150, 120, window=label_search_bar)

# Convert currency
convert_currency = Entry(window, justify=CENTER)
canvas.create_window(270, 150, height=30, width=100, window=convert_currency)

# label the to currency
label_convert_currency = Label(window, text="To (ex: CAD):")
label.config(font=('helvetica', 14))
canvas.create_window(270, 120, window=label_convert_currency)

#create a button
button = Button(
    window,
    text="Convert Currency",
    width=25,
    height=3,
    bg="white",
    fg="black",
    font=('helvetica', 9, 'bold'),
    command=CurrencyConverter
    )

#place the button
canvas.create_window(275, 200, height=40,width=150, window=button)

#Mainloop
window.mainloop()

Although the code is a bit longer than expected, it’s actually quite simple. You just need to remember a few things:

  • You write texts with the Label widget
  • You create buttons with the Button widget
  • You create input bars with the Entry widget
  • You place them at the right location using the Canvas widget and create_window()

Happy Coding!

About the author

Kalyani Rajalingham

I'm a linux and code lover.