Mi-krater
Mi-krater

Reputation: 619

How to Change tkcalendar date?

this is probably a really simple question, but I can't seem to find the answer.

But how do I go about changing the date of a tkcalendar calendar without user input?

Right now I am creating a new calendar every time my program loops to certain screen and I feel that this is inefficient.

Example:


enter image description here

Thank you!

Upvotes: 0

Views: 3689

Answers (1)

j_4321
j_4321

Reputation: 16179

As indicated in the documentation, the Calendar class has a .selection_set() method to change the selected date. It takes in argument the date to be selected in the form of a datetime.date, a datetime.datetime or a string formated according to the locale used in the calendar.

Example:

import tkinter as tk
import tkcalendar as tkc
from datetime import date

root = tk.Tk()
cal = tkc.Calendar(root, year=1900, month=11, day=11)
cal.pack()

tk.Button(root, text="Change date", command=lambda: cal.selection_set(date(2001, 1, 18))).pack()

Alternatively, you can connect a StringVar to the calendar through the textvariable option and use it to get and set the selected date:

import tkinter as tk
import tkcalendar as tkc
from datetime import date

root = tk.Tk()
datevar = tk.StringVar(root, "11/11/1990")
cal = tkc.Calendar(root, textvariable=datevar, locale="en_US")
cal.pack()

tk.Button(root, text="Change date", command=lambda: datevar.set("01/18/2001")).pack()

Upvotes: 1

Related Questions