w3resource

Python Project - Basic Calendar App with Tkinter and PyQt5


Calendar App:

Create a basic calendar application that allows users to add events.

Input values:
User interacts with the calendar application by adding events, specifying event details such as date, time, and description.

Output value:
Visual representation of the calendar with added events and feedback on user actions (addition, deletion).

Example:

Input values:
1. Add an event
- Input event date: 2015-02-15
- Input event time: 10:00 AM
- Input event description: Meeting with the client.
Output value:
Calendar app displays the event "Meeting with client" on February 15, 2015, at 10:00 AM.
Input values:
2. Add another event
- Input event date: 2015-02-20
- Input event time: 2:30 PM
- Input event description: Team brainstorming session
Output value:
Calendar app displays the event "Team brainstorming session" on February 20, 2015, at 2:30 PM.
Input values:
3. Delete an event
- Input event date to delete: 2015-02-15
- Input event time to delete: 10:00 AM
Output value:
Calendar app removes "Meeting with client" from February 15, 2015.
Input values:
4. View the calendar
Output value:
Calendar app displays all scheduled events for the month.

Here are two different solutions for a Calendar Application that allows users to add, delete, and view events with a simple user interface. Each solution uses different frameworks: Tkinter for the first solution and PyQt5 for the second.

Solution 1: Calendar App Using Tkinter

This solution uses the Tkinter library, which is a built-in GUI toolkit in Python, to create a basic calendar application with a simple user interface.

Code:

 # Solution 1: Calendar App Using Tkinter

from tkinter import Tk, Label, Button, Entry, StringVar, messagebox
from tkcalendar import Calendar
import datetime

class CalendarApp:
    """Class to create a Calendar Application using Tkinter."""
    
    def __init__(self, root):
        """Initialize the CalendarApp with the main Tkinter window."""
        self.root = root
        self.root.title("Basic Calendar App")
        self.events = {}  # Dictionary to store events
        
        # Calendar widget
        self.cal = Calendar(root, selectmode='day', year=2024, month=1, day=1)
        self.cal.grid(row=0, column=0, columnspan=4, padx=10, pady=10)
        
        # Event details entry fields
        self.date_var = StringVar()
        self.time_var = StringVar()
        self.desc_var = StringVar()
        
        Label(root, text="Event Date (YYYY-MM-DD):").grid(row=1, column=0)
        self.date_entry = Entry(root, textvariable=self.date_var)
        self.date_entry.grid(row=1, column=1)

        Label(root, text="Event Time (HH:MM AM/PM):").grid(row=2, column=0)
        self.time_entry = Entry(root, textvariable=self.time_var)
        self.time_entry.grid(row=2, column=1)

        Label(root, text="Event Description:").grid(row=3, column=0)
        self.desc_entry = Entry(root, textvariable=self.desc_var)
        self.desc_entry.grid(row=3, column=1)
        
        # Add and Delete buttons
        add_button = Button(root, text="Add Event", command=self.add_event)
        add_button.grid(row=4, column=0, pady=10)

        delete_button = Button(root, text="Delete Event", command=self.delete_event)
        delete_button.grid(row=4, column=1, pady=10)

        view_button = Button(root, text="View Events", command=self.view_events)
        view_button.grid(row=4, column=2, pady=10)

    def add_event(self):
        """Add an event to the calendar."""
        event_date = self.date_var.get()
        event_time = self.time_var.get()
        event_desc = self.desc_var.get()

        # Validate input
        if not event_date or not event_time or not event_desc:
            messagebox.showwarning("Input Error", "All fields are required.")
            return

        try:
            datetime.datetime.strptime(event_date, '%Y-%m-%d')
        except ValueError:
            messagebox.showwarning("Input Error", "Invalid date format. Use YYYY-MM-DD.")
            return

        # Add event to dictionary
        self.events[(event_date, event_time)] = event_desc
        messagebox.showinfo("Event Added", f"Event '{event_desc}' added on {event_date} at {event_time}.")
        self.clear_inputs()

    def delete_event(self):
        """Delete an event from the calendar."""
        event_date = self.date_var.get()
        event_time = self.time_var.get()

        # Validate input
        if not event_date or not event_time:
            messagebox.showwarning("Input Error", "Event date and time are required for deletion.")
            return

        # Remove event if exists
        if (event_date, event_time) in self.events:
            del self.events[(event_date, event_time)]
            messagebox.showinfo("Event Deleted", f"Event on {event_date} at {event_time} has been deleted.")
        else:
            messagebox.showwarning("Event Not Found", "No event found for the given date and time.")
        self.clear_inputs()

    def view_events(self):
        """View all events on the calendar."""
        events_list = "\n".join([f"{date} at {time}: {desc}" for (date, time), desc in self.events.items()])
        if events_list:
            messagebox.showinfo("All Events", events_list)
        else:
            messagebox.showinfo("No Events", "No events found.")

    def clear_inputs(self):
        """Clear the input fields."""
        self.date_var.set("")
        self.time_var.set("")
        self.desc_var.set("")

# Run the Tkinter calendar application
root = Tk()
app = CalendarApp(root)
root.mainloop() 

Output:

Python: Calender App using Tkinter view events.

Python: Calender App using Tkinter add events.

Explanation:

  • Tkinter Setup:
    • Creates a main window using Tkinter and initializes the calendar with the tkcalendar library.
  • Event Dictionary:
    • Uses a dictionary (self.events) to store events with keys as (date, time) tuples and values as event descriptions.
  • Adding Events:
    • Users input the date, time, and description of the event, which is then validated and added to the event dictionary.
  • Deleting Events:
    • Deletes events by matching the date and time provided by the user.
  • Viewing Events:
    • Displays all events stored in the dictionary using a messagebox.

Solution 2: Calendar App Using PyQt5

This solution uses the PyQt5 library to create a calendar application with a graphical user interface.

Code:

# Solution 2: Calendar App Using PyQt5

from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QVBoxLayout, QWidget, QLineEdit, QMessageBox, QCalendarWidget
import sys

class CalendarApp(QMainWindow):
    """Class to create a Calendar Application using PyQt5."""

    def __init__(self):
        """Initialize the CalendarApp with the main PyQt5 window."""
        super().__init__()
        self.setWindowTitle("Basic Calendar App")
        self.setGeometry(100, 100, 400, 400)
        self.events = {}  # Dictionary to store events

        # Set up the user interface
        self.setup_ui()

    def setup_ui(self):
        """Set up the user interface with widgets."""
        central_widget = QWidget()
        layout = QVBoxLayout()

        # Calendar widget
        self.calendar = QCalendarWidget(self)
        layout.addWidget(self.calendar)

        # Event details entry fields
        self.date_input = QLineEdit(self)
        self.date_input.setPlaceholderText("Enter Date (YYYY-MM-DD)")
        layout.addWidget(self.date_input)

        self.time_input = QLineEdit(self)
        self.time_input.setPlaceholderText("Enter Time (HH:MM AM/PM)")
        layout.addWidget(self.time_input)

        self.desc_input = QLineEdit(self)
        self.desc_input.setPlaceholderText("Enter Event Description")
        layout.addWidget(self.desc_input)

        # Add, Delete, and View buttons
        add_button = QPushButton("Add Event", self)
        add_button.clicked.connect(self.add_event)
        layout.addWidget(add_button)

        delete_button = QPushButton("Delete Event", self)
        delete_button.clicked.connect(self.delete_event)
        layout.addWidget(delete_button)

        view_button = QPushButton("View Events", self)
        view_button.clicked.connect(self.view_events)
        layout.addWidget(view_button)

        central_widget.setLayout(layout)
        self.setCentralWidget(central_widget)

    def add_event(self):
        """Add an event to the calendar."""
        event_date = self.date_input.text()
        event_time = self.time_input.text()
        event_desc = self.desc_input.text()

        # Validate input
        if not event_date or not event_time or not event_desc:
            QMessageBox.warning(self, "Input Error", "All fields are required.")
            return

        # Add event to dictionary
        self.events[(event_date, event_time)] = event_desc
        QMessageBox.information(self, "Event Added", f"Event '{event_desc}' added on {event_date} at {event_time}.")
        self.clear_inputs()

    def delete_event(self):
        """Delete an event from the calendar."""
        event_date = self.date_input.text()
        event_time = self.time_input.text()

        # Validate input
        if not event_date or not event_time:
            QMessageBox.warning(self, "Input Error", "Event date and time are required for deletion.")
            return

        # Remove event if exists
        if (event_date, event_time) in self.events:
            del self.events[(event_date, event_time)]
            QMessageBox.information(self, "Event Deleted", f"Event on {event_date} at {event_time} has been deleted.")
        else:
            QMessageBox.warning(self, "Event Not Found", "No event found for the given date and time.")
        self.clear_inputs()

    def view_events(self):
        """View all events on the calendar."""
        events_list = "\n".join([f"{date} at {time}: {desc}" for (date, time), desc in self.events.items()])
        if events_list:
            QMessageBox.information(self, "All Events", events_list)
        else:
            QMessageBox.information(self, "No Events", "No events found.")

    def clear_inputs(self):
        """Clear the input fields."""
        self.date_input.clear()
        self.time_input.clear()
        self.desc_input.clear()

# Run the PyQt5 calendar application
app = QApplication(sys.argv)
window = CalendarApp()
window.show()
sys.exit(app.exec_()) 

Output:

Python: Calender App.

Explanation:

  • PyQt5 Setup:
    • Uses PyQt5 to create a GUI application with a calendar widget, input fields, and buttons for user interaction.
  • Event Storage:
    • Stores events in a dictionary (self.events) with keys as (date, time) and values as event descriptions.
  • Add Event:
    • Adds an event after validating the input fields for date, time, and description.
  • Delete Event:
    • Deletes an event by matching the provided date and time.
  • View Events:
    • Displays all scheduled events in a message box.
  • Clear Inputs:
    • Clears the input fields after adding or deleting events.

Both solutions effectively create a basic calendar application with event management functionality using two different GUI libraries (Tkinter and PyQt5). Each provides a different approach to creating a graphical user interface for a calendar app.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/projects/python/python-calendar-app-project.php