如何在 tkcalendar (Python) 中获取 DateEntry 的选定日期?

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

我有一个 tkcalendar,它是日历、DateEntry 的预定义小部件,我正在尝试获取 用户为 DateEntry 选择的日期。 虽然有使用 "selection_get()" 提取日历小部件的选定日期的规定,但我找不到 DateEntry 的任何内容。

我已经尝试了 get_date(),get(),_date(), cget(), ._selection() 等等,但他们似乎 return/print 用户-选定的日期。 请帮忙,如果需要任何补充信息,请告诉我

代码[摘自简单的 tkcalendar 教程]:

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():
    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)
    print(cal.cget(DateEntry))

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()

您提到您已经尝试 get_date() 但它没有用,但这实际上是正确的功能。

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()

如果您想在每次更改时获取日期,您可以使用事件绑定。来自 the documentation:

  • Virtual Events

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

因此您可以将获取日期的函数绑定到 <<CalendarSelected>> 事件:

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)