레이블이 Tkinter Tutorial인 게시물을 표시합니다. 모든 게시물 표시
레이블이 Tkinter Tutorial인 게시물을 표시합니다. 모든 게시물 표시

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.

Python Number Guessing Game (GUI) - Tkinter Tutorial & Code

 




import tkinter as tk
import random
from tkinter import messagebox

def check_guess():
    """Checks the user's guess against the answer."""
    global guesses_taken
    guesses_taken += 1

    try:
        guess = int(guess_entry.get())
    except ValueError:
        messagebox.showerror("Error", "Please enter a valid number.")
        return

    if guess < answer:
        result_label.config(text="Too low!")
    elif guess > answer:
        result_label.config(text="Too high!")
    else:
        result_label.config(text=f"Congratulations! You guessed the number in {guesses_taken} guesses!")
        guess_button.config(state=tk.DISABLED)  # Disable the button after winning
        guess_entry.config(state=tk.DISABLED)  # Disable the entry field

def new_game():
    """Starts a new game."""
    global answer, guesses_taken
    answer = random.randint(1, 100)
    guesses_taken = 0
    result_label.config(text="")
    guess_entry.delete(0, tk.END)  # Clear the entry field
    guess_button.config(state=tk.NORMAL)  # Enable the button
    guess_entry.config(state=tk.NORMAL)  # Enable the entry field

# --- Main Window Setup ---
window = tk.Tk()
window.title("Number Guessing Game")
window.geometry("400x200")  # Set window size

# --- Widgets ---
instruction_label = tk.Label(window, text="Guess a number between 1 and 100:")
instruction_label.pack(pady=10)

guess_entry = tk.Entry(window)
guess_entry.pack()

guess_button = tk.Button(window, text="Guess", command=check_guess)
guess_button.pack(pady=5)

result_label = tk.Label(window, text="")
result_label.pack()

new_game_button = tk.Button(window, text="New Game", command=new_game)
new_game_button.pack(pady=10)

# --- Initialize Game ---
answer = random.randint(1, 100)
guesses_taken = 0

window.mainloop()

-----------------------------------------------------------------------------------------

How to Run:

  1. Save the Code: Copy the code above and save it as a .py file (e.g., number_guessing_game.py).

  2. Run:

    • Command Prompt or PowerShell:

      • Navigate to the directory where you saved the file.

      • Type python number_guessing_game.py and press Enter.

    • IDLE (Python GUI):

      • Open IDLE.

      • Go to File > Open and open the Python file you saved.

      • Select Run > Run Module or press F5.

Code Explanation:

  • import random: Imports the random module to generate random numbers.

  • number_guessing_game() function: Contains the main logic of the game.

  • random.randint(1, 100): Generates a random integer between 1 and 100 (inclusive).

  • input("Enter your guess: "): Prompts the user to enter a guess.

  • int(): Converts the input string to an integer. Includes ValueError exception handling to display an error message for invalid input.

  • if/elif/else: Checks if the user's guess is too low, too high, or correct.

  • while True: Continues the loop until the user guesses the correct number.

  • break: Exits the loop when the correct number is guessed.

  • if __name__ == "__main__":: Ensures that the number_guessing_game() function is called only when the script is executed directly.



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...