Pythone reminders app code error (beginer) TypeError: can only concatenate str (not “int”) to str

  Kiến thức lập trình

This is the coding eror

runfile('C:Python Reminders app/Reminders.py', wdir='C:/Users/Python Reminders app')
Exception in Tkinter callback
Traceback (most recent call last):
  File "C:Usersanacond/a3Libtkinter__init__.py", line 1948, in __call__
    return self.func(*args)
           ^^^^^^^^^^^^^^^^
  File "c:userspython reminders appreminders.py", line 67, in <lambda>
    tk.Button(self.calendar_window, text="OK", command=lambda idx=index: self.set_selected_date(idx)).pack(pady=5)
                                                                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "c:userspython reminders appreminders.py", line 82, in set_selected_date
    self.save_tasks()
  File "c:userspython reminders appreminders.py", line 31, in save_tasks
    for i, (goal_entry, deadline) in enumerate(self.goal_entries, start=1):
           ^^^^^^^^^^^^^^^^^^^^^^
  File "C:anaconda3Libtkinter__init__.py", line 1708, in cget
    return self.tk.call(self._w, 'cget', '-' + key)
                                         ~~~~^~~~~
TypeError: can only concatenate str (not "int") to str
Exception in Tkinter callback
Traceback (most recent call last):
  File , line 1948, in __call__
    return self.func(*args)
           ^^^^^^^^^^^^^^^^
  File "c:, line 103, in done
    self.save_tasks()
  File , line 31, in save_tasks
    for i, (goal_entry, deadline) in enumerate(self.goal_entries, start=1):
           ^^^^^^^^^^^^^^^^^^^^^^
  File , line 1708, in cget
    return self.tk.call(self._w, 'cget', '-' + key)
                                         ~~~~^~~~~
TypeError: can only concatenate str (not "int") to str

It is spose to save the data in an excel sheet but it gives this error and i have recheked and redone the save task but it doesn’t fix anything. I know some of the extensions are unnecessary but i plane on using them in the future. the excel file they need to go in is task.xlsx. I am a beginner to coding thus why i am hear. If you need any more info for help ples ask I can provide that.

This is the code:

    import tkinter as tk
    import tkcalendar as tkc
    from tkinter import messagebox, ttk
    from datetime import datetime, date, timedelta
    import threading
    from plyer import notification
    from openpyxl import Workbook, load_workbook

    class GoalApp:
        def __init__(self, master):
            self.master = master
            self.master.title("Daily Goals App")

            self.goal_entries = []  # List to store all goal entry widgets
            self.load_tasks()  # Load tasks from Excel sheet
            self.create_widgets()
       def load_tasks(self):
            try:
                workbook = load_workbook("tasks.xlsx")
                sheet = workbook.active
                for row in sheet.iter_rows(values_only=True):
                    goal_entry = row[0]
                    deadline = row[1]
                    self.goal_entries.append((goal_entry, deadline))
                workbook.close()
            except FileNotFoundError:
                pass
        def save_tasks(self):
            workbook = Workbook()
            sheet = workbook.active
            for i, (goal_entry, deadline) in enumerate(self.goal_entries, start=1):
                sheet.cell(row=i, column=1, value=str(goal_entry))  # Convert to string
                sheet.cell(row=i, column=2, value=str(deadline))    # Convert to string
            workbook.save("tasks.xlsx")
        def create_widgets(self):
            self.goal_label = tk.Label(self.master, text="Enter Your Goals for Today:")
            self.goal_label.grid(row=0, column=0, sticky="w")

            self.add_goal_button = tk.Button(self.master, text="Add Goal", command=self.add_goal)
            self.add_goal_button.grid(row=0, column=1, padx=5)

            self.done_button = tk.Button(self.master, text="Done", command=self.done)
            self.done_button.grid(row=0, column=2, padx=5)

        def add_goal(self):
            current_row = len(self.goal_entries) + 1
        
            goal_entry = tk.Entry(self.master)
            goal_entry.grid(row=current_row, column=0, pady=5)
            self.goal_entries.append(goal_entry)
    
            date_button = tk.Button(self.master, text="Select Date", command=lambda idx=current_row: self.select_date(idx))
            date_button.grid(row=current_row, column=1, padx=5)
    
            # Add a label to display selected date next to the entry box
            selected_date_label = tk.Label(self.master, text="")
            selected_date_label.grid(row=current_row, column=2, padx=5)
            self.goal_entries[-1].selected_date_label = selected_date_label

        def select_date(self, index):
            self.calendar_window = tk.Toplevel(self.master)
            self.calendar_window.title("Select Deadline")
    
            self.calendar = tkc.Calendar(self.calendar_window, selectmode='day')
            self.calendar.pack(padx=10, pady=10)
    
            tk.Button(self.calendar_window, text="OK", command=lambda idx=index: self.set_selected_date(idx)).pack(pady=5)


        def set_selected_date(self, index):
            selected_date = self.calendar.get_date()
            if selected_date:
                try:
                    date_obj = datetime.strptime(selected_date, "%m/%d/%y").date()
                    formatted_date = date_obj.strftime("%Y-%m-%d")
                    self.goal_entries[index - 1].deadline = formatted_date  # Store the deadline in the goal entry widget
                    self.goal_entries[index - 1].selected_date_label.config(text=selected_date)  # Update the label with selected date
                    self.calendar_window.destroy()
                except ValueError:
                     messagebox.showerror("Error", "Invalid date format. Please select a date from the calendar.")
            # Save tasks to Excel sheet after updating
            self.save_tasks()
        def done(self):
            self.master.iconify()  # Minimize the window

            for entry in self.goal_entries:
                goal = entry.get()
                deadline = getattr(entry, "deadline", None)

                if deadline:
                    try:
                        goal_date = datetime.strptime(deadline, "%Y-%m-%d").date()
                        current_date = date.today()

                        if current_date <= goal_date:
                            days_until_deadline = (goal_date - current_date).days
                            for i in range(1, days_until_deadline + 1):
                                reminder_date = current_date + timedelta(days=i)
                                threading.Timer(30 * i, self.remind, args=[goal]).start()
                    except ValueError:
                        messagebox.showerror("Error", "Invalid date format. Please use YYYY-MM-DD.")
             # Save tasks to Excel sheet after updating
             self.save_tasks()

        def remind(self, goal):
            # Calculate the time until the next day
            now = datetime.now()
            tomorrow = now.replace(hour=0, minute=0, second=0, microsecond=0) + timedelta(days=1)
            time_until_tomorrow = (tomorrow - now).total_seconds()

            # Schedule the reminder for tomorrow
            threading.Timer(time_until_tomorrow, self.remind, args=[goal]).start()

            reminder_msg = f"Don't forget to: {goal}"
            notification.notify(
                title='Reminder',
                message=reminder_msg,
                app_name='Daily Goals App',
                timeout=10  # Set the notification timeout (in seconds)
            )

            result = messagebox.askyesno("Reminder", reminder_msg + "nnDo you want to mark this task as done?")
        
            if result:
                messagebox.showinfo("Task Marked as Done", "You won't receive further reminders for this task.")
                 return  # Stop further reminders for this task

    def main():
        root = tk.Tk()
        app = GoalApp(root)
        root.mainloop()

    if __name__ == "__main__":
       main()`

New contributor

Muhammad Ismail is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT