如何在tkinter中创建日期选择器?

55 投票
8 回答
122513 浏览
提问于 2025-04-16 08:32

有没有什么标准的方法让tkinter应用程序让用户选择日期呢?

8 个回答

11

试试下面这个:

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

其中,tkcalendar 这个库需要通过命令 pip install tkcalendar 下载和安装。

12

我找不到相关的信息。对于将来想做这个的人:

我使用了 tkSimpleDialogttkcalendar.py(并根据 这个 StackOverflow 的帖子做了一些修改)来制作一个 CalendarDialog。这三个文件的修改版本可以在我的 github 上找到。

下面是我在 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()
31

如果还有人需要这个,这里有一段简单的代码,可以用来创建一个日历和日期选择器,使用的是tkcalendar这个包。

pip install tkcalendar (用来安装这个包)

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

撰写回答