How do I create a date picker in tkinter?

前端 未结 7 1409
借酒劲吻你
借酒劲吻你 2020-11-28 09:45

Is there any standard way tkinter apps allow the user to choose a date?

7条回答
  •  温柔的废话
    2020-11-28 10:23

    The answers here provide most of what you asked for, but I felt none of them were completely satisfying. As a Tkinter newbie, I needed more hand-holding. My complaints:

    1. Assuming I want the calendar to default to a 2012 date rather than today's date,
    2. Not returning the result as a variable for future use,
    3. An unnecessary top layer menu before getting to the calendar, and
    4. Not cleaning up the windows and exiting mainloop after a selection has been made.

    So with gratitude to the previous answers which helped me immensely, here's my version.

    def get_date():
        import tkinter as tk
        from tkinter import ttk
        from tkcalendar import Calendar, DateEntry
    
        def cal_done():
            top.withdraw()
            root.quit()
    
        root = tk.Tk()
        root.withdraw() # keep the root window from appearing
    
        top = tk.Toplevel(root)
    
        cal = Calendar(top,
                       font="Arial 14", selectmode='day',
                       cursor="hand1")
        cal.pack(fill="both", expand=True)
        ttk.Button(top, text="ok", command=cal_done).pack()
    
        selected_date = None
        root.mainloop()
        return cal.selection_get()
    
    selection = get_date()
    print(selection)
    

提交回复
热议问题