Making a button on tkcalendar to colour background of selected days

276 views Asked by At

I am trying to obtain the following
enter image description here
(used an example from the tkcalendar page). But I want it with a button, so that when I press it, the date becomes coloured like that. I can't seem to make calevent_create and tag_config work though.

Can anybody help me with it?

Here is my code:

# Import Required Library
from tkinter import *
from tkcalendar import Calendar
from datetime import date

# Create Object
root = Tk()

# Set geometry
root.geometry("400x400")

# Add Calendar
cal = Calendar(root, firstweekday="monday", selectmode='day', year=2023, month=1, day=1,
               background="black", disabledbackground="black", bordercolor="white",
               headersbackground="black", normalbackground="black", foreground='white',
               normalforeground='white', headersforeground='white', date_pattern="dd-mm-y")

cal.pack(pady=20)


def grad_date():
    dt = cal.get_date()

    date.config(text="Selected Date is completed: " + dt)
    cal.calevent_create(dt, 'Hello World', tags= "Message")

    cal.tag_config("Message", background='red', foreground='yellow')


# Add Button and Label
Button(root, text="Complete Date",
       command=grad_date).pack(pady=20)

date = Label(root, text="")
date.pack(pady=20)

# Execute Tkinter
root.mainloop()

What I expect to happen is: When I press the button on the selected date, the calendar date should turn its background colour to the one I chose. Kind of like making sure a task in a day has been completed.

1

There are 1 answers

0
tetris programming On

the dt that you get from cal.get_date() is of format string. The method cal.calevent_create() uses the format datetime which means that dt is incompatible with that method. This is why you get an error like:

TypeError: date option should be a <class 'datetime.date'> instance

To transform dt into a datetime you can use:

dt=datetime.datetime.strptime(dt, "%d-%m-%Y")

In your case the function grad_date() could look like this:

def grad_date():
    dt = cal.get_date()
    date.config(text="Selected Date is completed: " + dt)
    dt = datetime.datetime.strptime(dt, "%d-%m-%Y")
    cal.calevent_create(dt, 'Hello World', tags= "Message")
    cal.tag_config("Message", background='red', foreground='yellow')