2025년 3월 19일 수요일

Python To-Do List GUI: Build a Simple Task Manager with Tkinter

 

todo_list_gui.py



import tkinter as tk
from tkinter import messagebox

def add_task():
    """Adds a new task to the to-do list."""
    task = task_entry.get()
    if task:
        task_list.insert(tk.END, task)
        task_entry.delete(0, tk.END)
    else:
        messagebox.showwarning("Warning", "Please enter a task.")

def delete_task():
    """Deletes the selected task from the to-do list."""
    try:
        selected_index = task_list.curselection()[0]
        task_list.delete(selected_index)
    except IndexError:
        messagebox.showinfo("Info", "Please select a task to delete.")

def mark_complete():
    """Marks the selected task as complete (crosses it out)."""
    try:
        selected_index = task_list.curselection()[0]
        task = task_list.get(selected_index)
        task_list.delete(selected_index)
        task_list.insert(selected_index, f"✅ {task}")  # Add a checkmark
    except IndexError:
        messagebox.showinfo("Info", "Please select a task to mark as complete.")

# --- Main Window Setup ---
window = tk.Tk()
window.title("To-Do List")
window.geometry("400x400")

# --- Widgets ---
task_label = tk.Label(window, text="Enter Task:")
task_label.grid(row=0, column=0, padx=5, pady=5)

task_entry = tk.Entry(window, width=30)
task_entry.grid(row=0, column=1, padx=5, pady=5)

add_button = tk.Button(window, text="Add Task", command=add_task)
add_button.grid(row=1, column=0, columnspan=2, padx=5, pady=5)

task_list = tk.Listbox(window, width=40, height=10)
task_list.grid(row=2, column=0, columnspan=2, padx=5, pady=5)

delete_button = tk.Button(window, text="Delete Task", command=delete_task)
delete_button.grid(row=3, column=0, padx=5, pady=5)

complete_button = tk.Button(window, text="Mark Complete", command=mark_complete)
complete_button.grid(row=3, column=1, padx=5, pady=5)

# --- Start the GUI ---
window.mainloop()

-

How to Run:

  1. Save the Code: Save the code as a .py file (e.g., todo_list_gui.py).
  2. Run: Open a command prompt or terminal on Windows and navigate to the directory where you saved the file. Then, run the script using python todo_list_gui.py.

This code creates a window with an entry field for adding tasks, a listbox to display the tasks, and buttons for adding, deleting, and marking tasks as complete. It provides a user-friendly interface for managing your to-do list. I've included a checkmark to visually indicate completed tasks.

Python To-Do List GUI - Code Explanation (User-Friendly)

This code creates a simple to-do list application with a graphical user interface (GUI) using Python's tkinter library. Here's a breakdown of each part, explained in a way that's easy to understand:

1. Importing Libraries:



import tkinter as tk
from tkinter import messagebox
-
  • tkinter: This is Python's standard GUI library. It provides the tools to create windows, buttons, text boxes, and other visual elements. We import it as tk for convenience.
  • tkinter.messagebox: This module allows us to display pop-up messages (like warnings or information) to the user.

2. Defining Functions (What happens when you click a button):

  • add_task():
    • Gets the text the user typed into the task_entry (the text box).
    • Checks if the text is not empty. If it's empty, it shows a warning message.
    • If the text is valid, it adds the task to the task_list (the listbox where tasks are displayed).
    • Clears the task_entry so the user can type in the next task.
  • delete_task():
    • Tries to get the index of the task the user selected in the task_list.
    • If the user hasn't selected a task, it shows an information message.
    • If a task is selected, it deletes that task from the task_list.
  • mark_complete():
    • Tries to get the index of the task the user selected.
    • If no task is selected, it shows an information message.
    • If a task is selected:
      • It gets the text of the selected task.
      • It deletes the task from the list.
      • It re-inserts the task with a "✅" (checkmark) at the beginning to indicate it's complete.

3. Setting Up the Main Window:



window = tk.Tk()
window.title("To-Do List")
window.geometry("400x400")

-
  • window = tk.Tk(): Creates the main window of the application.
  • window.title("To-Do List"): Sets the title of the window (what appears in the title bar).
  • window.geometry("400x400"): Sets the size of the window to 400 pixels wide and 400 pixels high.

4. Creating Widgets (The visual elements):

  • task_label = tk.Label(window, text="Enter Task:"): Creates a label that displays the text "Enter Task:".
  • task_entry = tk.Entry(window, width=30): Creates a text box where the user can type in tasks. width=30 sets the width of the text box.
  • add_button = tk.Button(window, text="Add Task", command=add_task): Creates a button that says "Add Task". command=add_task tells the button to call the add_task() function when it's clicked.
  • task_list = tk.Listbox(window, width=40, height=10): Creates a listbox where the tasks will be displayed. width and height control the size of the listbox.
  • delete_button = tk.Button(window, text="Delete Task", command=delete_task): Creates a button to delete tasks.
  • complete_button = tk.Button(window, text="Mark Complete", command=mark_complete): Creates a button to mark tasks as complete.

5. Arranging Widgets (Using grid):

The grid() method is used to arrange the widgets in a grid layout within the window. row and column specify the position of the widget in the grid. padx and pady add padding around the widget.

6. Starting the GUI:


window.mainloop()
-
  • window.mainloop(): This starts the Tkinter event loop. The event loop listens for user interactions (like button clicks, key presses, etc.) and keeps the window open until the user closes it.

How it Works Together:

The code creates a window with a text box, buttons, and a listbox. When the user types a task into the text box and clicks "Add Task," the add_task() function adds the task to the listbox. When the user selects a task and clicks "Delete Task," the delete_task() function removes the task from the listbox. When the user selects a task and clicks "Mark Complete," the mark_complete() function adds a checkmark to the beginning of the task in the listbox. The mainloop() function keeps the window open and responsive to user interactions.

댓글 없음:

댓글 쓰기

Recommended Posts

Resolving: "error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools"" in AUTOMATIC1111

  Resolving: "error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools"" in AUTOM...