How to get the selected date for DateEntry in tkcalendar (Python)?

空扰寡人 提交于 2019-12-06 07:32:52

You mention you have tried get_date() and it didn't work, but that's actually the right function.

import tkinter as tk
from tkinter import ttk
from tkcalendar import Calendar, DateEntry

def calendar_view():
    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 dateentry_view():
    def print_sel():
        print(cal.get_date())
    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)
    ttk.Button(top, text="ok", command=print_sel).pack()

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

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

root.mainloop()

If you want to get the date every time it is changed you can use an event binding. From the documentation:

  • Virtual Events

A <<CalendarSelected>> event is generated each time the user selects a day with the mouse.

So you can bind the function that gets the date to the <<CalendarSelected>> event:

def dateentry_view():
    def print_sel(e):
        print(cal.get_date())
    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)
    cal.bind("<<DateEntrySelected>>", print_sel)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!