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

2024-05-16 22:56:05 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我已经尝试过get_date()、get()、_date()、cget()、.u selection()等多种方法,但它们似乎没有返回/打印用户选择的日期。 请帮忙,如果需要补充信息请告诉我

代码[摘自一个简单的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()

Tags: textviewgettoprootcalendarpacktk