Building Simple Python Applications with Tkinter: A Calculator and To-Do List

Welcome to the world of Python GUI applications! In this post, we’ll explore two straightforward yet practical applications built using the Tkinter library. Whether you’re a beginner looking to enhance your Python skills or someone seeking to create intuitive user interfaces, these examples are a great starting point.

Exploring Python Tkinter Applications

CalculatorApp

Let’s dive into the first example, the “CalculatorApp.” This application showcases the power of Tkinter in creating a user-friendly calculator with basic arithmetic operations. Follow along as we break down the code and understand how to implement a simple calculator interface.

TodoApp

Moving on to the second example, the “TodoApp” demonstrates the versatility of Tkinter in building a to-do list manager. Learn how to create an interactive to-do list with features such as adding tasks, removing them, and clearing the entire list. This practical example can serve as a foundation for more complex project developments.

Why Tkinter?

Tkinter, Python’s standard GUI toolkit, is an excellent choice for beginners due to its simplicity and ease of use. These applications not only provide functional utility but also serve as educational tools for understanding the basics of GUI programming in Python.

Whether you’re interested in building your first GUI application or just exploring Tkinter capabilities, these examples offer a hands-on approach to get you started. Let’s unravel the code, understand the key components, and embark on a journey to enhance your Python programming skills.

Code

Calculator App

import tkinter as tk

class CalculatorApp:
    def __init__(self, root):
        self.root = root
        self.root.title("Calculator")

        # Variable to store the expression
        self.expression = tk.StringVar()

        # Flag to check if the last action was an evaluation of the result
        self.last_evaluation = False

        # Entry to display the expression
        entry = tk.Entry(root, textvariable=self.expression, font=('Helvetica', 14), justify='right', bd=10)
        entry.grid(row=0, column=0, columnspan=4)

        # Numeric and operator buttons
        buttons = [
            '7', '8', '9', '/',
            '4', '5', '6', '*',
            '1', '2', '3', '-',
            '0', '.', '=', '+',
            'C', '←', '%', '±'  # Added buttons
        ]

        # Adding buttons to the grid
        row_val = 1
        col_val = 0
        for button in buttons:
            tk.Button(root, text=button, padx=20, pady=20, font=('Helvetica', 12),
                      command=lambda b=button: self.on_button_click(b)).grid(row=row_val, column=col_val)
            col_val += 1
            if col_val > 3:
                col_val = 0
                row_val += 1

    def on_button_click(self, button):
        current_expression = self.expression.get()

        if button == '=':
            try:
                result = eval(current_expression)
                self.expression.set(result)
                self.last_evaluation = True
            except Exception as e:
                self.expression.set("Error")
        elif button == 'C':
            self.expression.set('')
            self.last_evaluation = False
        elif button == '←':
            if not self.last_evaluation:
                new_expression = current_expression[:-1]
                self.expression.set(new_expression)
        elif button == '%':
            if not self.last_evaluation:
                try:
                    result = eval(current_expression) / 100
                    self.expression.set(result)
                    self.last_evaluation = True
                except Exception as e:
                    self.expression.set("Error")
        elif button == '±':
            if not self.last_evaluation:
                if current_expression and current_expression[0] == '-':
                    self.expression.set(current_expression[1:])
                else:
                    self.expression.set('-' + current_expression)
        else:
            if self.last_evaluation:
                self.expression.set(str(button))
                self.last_evaluation = False
            else:
                new_expression = current_expression + str(button)
                self.expression.set(new_expression)

if __name__ == "__main__":
    root = tk.Tk()
    app = CalculatorApp(root)
    root.mainloop()

CalculatorApp:

The CalculatorApp is a simple calculator application implemented using the Tkinter library in Python. It provides a basic graphical user interface for performing arithmetic operations.

  • Class Initialization:
    • The class is initialized with a root window.
    • The window title is set to “Calculator.”
  • Attributes:
    • self.expression: A Tkinter StringVar to store the mathematical expression.
    • self.last_evaluation: A flag to check if the last action was an evaluation.
  • GUI Components:
    • Entry: Displays the expression.
    • Numeric and operator buttons: Arranged in a grid layout for user input.
  • Methods:
    • on_button_click: Handles button clicks, updates the expression, and performs calculations based on the button pressed.
  • Main Block:
    • Creates an instance of the CalculatorApp class and runs the Tkinter main loop.

Code

To-Do List App

import tkinter as tk
from tkinter import messagebox

class TodoApp:
    def __init__(self, root):
        self.root = root
        self.root.title("To-Do List App")

        # List to store tasks
        self.tasks = []

        # Entry to add a new task
        self.entry = tk.Entry(root, width=40)
        self.entry.grid(row=0, column=0, padx=10, pady=10)

        # Button to add a task
        add_button = tk.Button(root, text="Add Task", command=self.add_task)
        add_button.grid(row=0, column=1, padx=10, pady=10)

        # Listbox to display tasks
        self.listbox = tk.Listbox(root, width=50, height=10)
        self.listbox.grid(row=1, column=0, columnspan=2, padx=10, pady=10)

        # Button to remove the selected task
        remove_button = tk.Button(root, text="Remove Task", command=self.remove_task)
        remove_button.grid(row=2, column=0, padx=10, pady=10)

        # Button to clear the task list
        clear_button = tk.Button(root, text="Clear List", command=self.clear_tasks)
        clear_button.grid(row=2, column=1, padx=10, pady=10)

    def add_task(self):
        task = self.entry.get()
        if task:
            self.tasks.append(task)
            self.listbox.insert(tk.END, task)
            self.entry.delete(0, tk.END)
        else:
            messagebox.showwarning("Warning", "Enter a task!")

    def remove_task(self):
        selected_task_index = self.listbox.curselection()
        if selected_task_index:
            self.listbox.delete(selected_task_index)
            del self.tasks[selected_task_index[0]]

    def clear_tasks(self):
        self.listbox.delete(0, tk.END)
        self.tasks.clear()

if __name__ == "__main__":
    root = tk.Tk()
    app = TodoApp(root)
    root.mainloop()

TodoApp:

The TodoApp is a basic to-do list application created with Tkinter in Python. It allows users to add, remove, and clear tasks from a list.

  • Class Initialization:
    • The class is initialized with a root window.
    • The window title is set to “To-Do List App.”
  • Attributes:
    • self.tasks: A list to store tasks.
  • GUI Components:
    • Entry: Allows users to input new tasks.
    • Listbox: Displays the list of tasks.
    • Buttons: Add Task, Remove Task, and Clear List.
  • Methods:
    • add_task: Adds a task to the list.
    • remove_task: Removes the selected task from the list.
    • clear_tasks: Clears all tasks from the list.
  • Main Block:
    • Creates an instance of the TodoApp class and runs the Tkinter main loop.

Both applications use Tkinter for the graphical user interface. The CalculatorApp provides a simple calculator functionality, while the TodoApp allows users to manage a to-do list with basic operations.

Conclusion

In conclusion, exploring the creation of Python applications using Tkinter has provided a valuable insight into the world of graphical user interfaces. The “CalculatorApp” and “TodoApp” exemplify the simplicity and effectiveness of Tkinter in building functional yet straightforward applications.

As we delved into the code of these applications, we discovered how Tkinter facilitates the creation of responsive and interactive user interfaces with minimal effort. From a basic calculator that performs arithmetic operations to a to-do list manager with task management functionalities, these examples showcase the versatility of Tkinter in meeting various user interface needs.

By understanding the principles behind these applications, you’ve gained a foundation for more complex GUI projects. Tkinter’s accessibility makes it an ideal choice for those starting their journey into GUI programming with Python.

As you continue your exploration of Tkinter or delve into other Python libraries for GUI development, remember that these examples serve as stepping stones toward creating more advanced and feature-rich applications. The hands-on experience gained from dissecting and implementing these applications will undoubtedly prove beneficial as you embark on your programming endeavors.

Whether you are a novice seeking to expand your Python skills or an experienced developer exploring Tkinter’s capabilities, these examples have provided valuable insights and practical knowledge. Use this newfound understanding to fuel your passion for Python programming and GUI development, and let your creativity flourish in building innovative applications. Happy coding!