How do I create a date picker in tkinter?

Solution 1:

In case anyone still needs this - here's a simple code to create a Calendar and DateEntry widget using tkcalendar package.

pip install tkcalendar (for installing the package)

try:
    import tkinter as tk
    from tkinter import ttk
except ImportError:
    import Tkinter as tk
    import ttk

from tkcalendar import Calendar, DateEntry

def example1():
    def print_sel():
        print(cal.selection_get())

    top = tk.Toplevel(root)

    cal = Calendar(top,
                   font="Arial 14", selectmode='day',
                   cursor="hand1", year=2018, month=2, day=5)
    cal.pack(fill="both", expand=True)
    ttk.Button(top, text="ok", command=print_sel).pack()

def example2():
    top = tk.Toplevel(root)

    ttk.Label(top, text='Choose date').pack(padx=10, pady=10)

    cal = DateEntry(top, width=12, background='darkblue',
                    foreground='white', borderwidth=2)
    cal.pack(padx=10, pady=10)

root = tk.Tk()
s = ttk.Style(root)
s.theme_use('clam')

ttk.Button(root, text='Calendar', command=example1).pack(padx=10, pady=10)
ttk.Button(root, text='DateEntry', command=example2).pack(padx=10, pady=10)

root.mainloop()

Solution 2:

Not as far as I could find. For anyone who wants to do this in the future:

I used tkSimpleDialog and ttkcalendar.py (with modifications from this SO post) to make a CalendarDialog. The modified versions of the three files are available on my github.

Below is the code in my CalendarDialog.py:

import Tkinter

import ttkcalendar
import tkSimpleDialog

class CalendarDialog(tkSimpleDialog.Dialog):
    """Dialog box that displays a calendar and returns the selected date"""
    def body(self, master):
        self.calendar = ttkcalendar.Calendar(master)
        self.calendar.pack()

    def apply(self):
        self.result = self.calendar.selection

# Demo code:
def main():
    root = Tkinter.Tk()
    root.wm_title("CalendarDialog Demo")

    def onclick():
        cd = CalendarDialog(root)
        print cd.result

    button = Tkinter.Button(root, text="Click me to see a calendar!", command=onclick)
    button.pack()
    root.update()

    root.mainloop()


if __name__ == "__main__":
    main()

Solution 3:

Try with the following:

from tkinter import *

from tkcalendar import Calendar,DateEntry

root = Tk()

cal = DateEntry(root,width=30,bg="darkblue",fg="white",year=2010)

cal.grid()

root.mainloop()

where tkcalendar library should be downloaded and installed through pip install tkcalender command.

Solution 4:

No, but you can get it from the user as a datetime element from a formatted string..

Example:

import datetime

userdatestring = '2013-05-10'
thedate = datetime.datetime.strptime(userdatestring, '%Y-%m-%d') 

Check out http://docs.python.org/2/library/datetime.html#strftime-strptime-behavior. It's handy, although not the most user friendly way of getting a date.