Building a Simple GUI Application with Python’s Tkinter

–by Alauddin Sabari

Python’s Tkinter module is a powerful tool for creating graphical user interfaces (GUIs). Whether you’re a beginner looking to dive into GUI programming or an experienced developer wanting to create a simple desktop app, Tkinter has you covered. In this tutorial, we’ll build a step-by-step project: a Currency Converter App.

Table of Contents

  1. What is Tkinter?
  2. Setting Up Your Environment
  3. Creating the Main Window
  4. Adding Widgets
  5. Implementing Functionality
  6. Styling the Application
  7. Testing and Running the App
  8. Conclusion

What is Tkinter?

Tkinter is the standard GUI toolkit provided with Python. It allows you to create simple graphical user interfaces with buttons, labels, entry fields, and more. Tkinter is easy to learn and offers a wide range of widgets and tools for creating desktop applications.

Why Use Tkinter?

  • Cross-platform: Works on Windows, macOS, and Linux.
  • Built-in with Python: No need to install additional packages.
  • Simple and Easy to Learn: Great for beginners and quick prototypes.

Setting Up Your Environment

Before we dive into the code, make sure you have Python installed on your machine.

Step 1: Check if Tkinter is Installed

Tkinter comes pre-installed with most Python distributions. You can check if it’s available by running:

import tkinter
print("Tkinter is installed and ready to use!")

If you don’t encounter any errors, you’re good to go!

Step 2: Create a Project Folder

Let’s organize our project files:

mkdir currency_converter
cd currency_converter
touch main.py

Creating the Main Window

Let’s start by creating a basic window for our application.

Step 3: Writing the Boilerplate Code

Open main.py and add the following code:

import tkinter as tk

# Initialize the main window
root = tk.Tk()
root.title("Currency Converter")
root.geometry("400x300")

# Start the Tkinter event loop
root.mainloop()

Explanation:

  • tk.Tk() initializes the main application window.
  • .title() sets the window title.
  • .geometry() defines the window size.

Run the script:

python main.py

You should see a simple blank window pop up.


Adding Widgets

Now that we have a window, let’s add some widgets like labels, entry fields, and buttons.

Step 4: Adding Labels and Entry Fields

Update your code to include labels and entry fields:

# Currency Converter App
import tkinter as tk

# Initialize the main window
root = tk.Tk()
root.title("Currency Converter")
root.geometry("400x300")

# Add a label for the amount
amount_label = tk.Label(root, text="Enter Amount:", font=("Arial", 12))
amount_label.pack(pady=10)

# Add an entry field for the amount
amount_entry = tk.Entry(root, width=20)
amount_entry.pack()

# Add a label for the result
result_label = tk.Label(root, text="Converted Amount:", font=("Arial", 12))
result_label.pack(pady=20)

# Display the result
output = tk.Label(root, text="", font=("Arial", 14))
output.pack()

root.mainloop()

Explanation:

  • tk.Label() creates text labels.
  • tk.Entry() allows user input.

Implementing Functionality

Let’s add functionality to convert the amount using a predefined exchange rate.

Step 5: Adding a Convert Button

Add a button and a function to handle the conversion:

# Function to convert currency
def convert_currency():
    try:
        amount = float(amount_entry.get())
        converted = amount * 0.85  # Example: Convert USD to EUR
        output.config(text=f"€{converted:.2f}")
    except ValueError:
        output.config(text="Invalid input. Please enter a number.")

# Add a convert button
convert_button = tk.Button(root, text="Convert", command=convert_currency)
convert_button.pack(pady=10)

Explanation:

  • command=convert_currency binds the button to the conversion function.
  • .get() retrieves the user input from the entry field.
  • .config() updates the label with the conversion result.

Styling the Application

Let’s make our app visually appealing with some styles.

Step 6: Applying Styles

Modify your widgets to include styles:

# Change background color
root.config(bg="#f0f0f0")

# Add padding and styles
amount_label.config(bg="#f0f0f0", fg="#333")
result_label.config(bg="#f0f0f0", fg="#333")
output.config(bg="#f0f0f0", fg="#007acc", font=("Arial", 16, "bold"))
convert_button.config(bg="#007acc", fg="white", font=("Arial", 10, "bold"))

Testing and Running the App

Here’s the final code for your Currency Converter App:

import tkinter as tk

# Currency Converter App
def convert_currency():
    try:
        amount = float(amount_entry.get())
        converted = amount * 0.85  # USD to EUR conversion rate
        output.config(text=f"€{converted:.2f}")
    except ValueError:
        output.config(text="Invalid input. Please enter a number.")

# Initialize the main window
root = tk.Tk()
root.title("Currency Converter")
root.geometry("400x300")
root.config(bg="#f0f0f0")

# Widgets
amount_label = tk.Label(root, text="Enter Amount:", font=("Arial", 12), bg="#f0f0f0", fg="#333")
amount_label.pack(pady=10)

amount_entry = tk.Entry(root, width=20)
amount_entry.pack()

convert_button = tk.Button(root, text="Convert", command=convert_currency, bg="#007acc", fg="white")
convert_button.pack(pady=10)

result_label = tk.Label(root, text="Converted Amount:", font=("Arial", 12), bg="#f0f0f0", fg="#333")
result_label.pack(pady=20)

output = tk.Label(root, text="", font=("Arial", 14), bg="#f0f0f0", fg="#007acc")
output.pack()

root.mainloop()

Conclusion

Congratulations! You’ve just built your first Python GUI application using Tkinter. We covered the basics of creating windows, adding widgets, and styling your application. Tkinter is a versatile and powerful tool for building desktop apps, and we hope this tutorial inspires you to explore more.

Feel free to extend this project by adding features like:

  • Real-time exchange rates using an API
  • Dropdown menus for multiple currencies
  • Data validation for user input

Happy coding!


Additional Resources


Leave a Reply

Your email address will not be published. Required fields are marked *