2 min read

Python GUI App with Tkinter

This guide demonstrates how to create a simple desktop Graphical User Interface (GUI) application using tkinter, Python's standard GUI library. We will build a basic "To-Do List" application.

Modules Used:

  • tkinter: The standard Python interface to the Tcl/Tk GUI toolkit.

Installation

tkinter is included with most Python installations. You can verify it by running:

python -m tkinter

If a small window appears, you are good to go. On Linux, you might need to install it manually (e.g., sudo apt-get install python3-tk).

The Code

Save this as todo_app.py.

import tkinter as tk
from tkinter import messagebox

class TodoApp:
    def __init__(self, root):
        self.root = root
        self.root.title("Simple To-Do List")
        self.root.geometry("400x450")

        # 1. Entry Widget (Input)
        self.task_entry = tk.Entry(root, width=30, font=("Arial", 14))
        self.task_entry.pack(pady=20)

        # 2. Add Button
        self.add_button = tk.Button(root, text="Add Task", command=self.add_task, font=("Arial", 12))
        self.add_button.pack(pady=5)

        # 3. Listbox (Display)
        self.tasks_listbox = tk.Listbox(root, width=40, height=10, font=("Arial", 12))
        self.tasks_listbox.pack(pady=10, padx=10)

        # 4. Delete Button
        self.delete_button = tk.Button(root, text="Delete Selected", command=self.delete_task, font=("Arial", 12), bg="#ffcccc")
        self.delete_button.pack(pady=5)

        # Bind Enter key to add task
        self.root.bind('<Return>', lambda event: self.add_task())

    def add_task(self):
        task = self.task_entry.get()
        if task != "":
            self.tasks_listbox.insert(tk.END, task)
            self.task_entry.delete(0, tk.END)
        else:
            messagebox.showwarning("Warning", "You must enter a task.")

    def delete_task(self):
        try:
            # Get index of currently selected item
            selected_task_index = self.tasks_listbox.curselection()[0]
            self.tasks_listbox.delete(selected_task_index)
        except IndexError:
            messagebox.showwarning("Warning", "You must select a task to delete.")

if __name__ == "__main__":
    # Create the main window
    root = tk.Tk()

    # Initialize application
    app = TodoApp(root)

    # Start the event loop
    root.mainloop()

Usage

python todo_app.py
  1. Type a task in the input box.
  2. Click "Add Task" or press Enter.
  3. Select a task and click "Delete Selected" to remove it.

programming/python/python