Python tkinter实现日期选择器

时间:2022-10-23 07:31:04

如何利用python的tkinter模块实现日期选择器,根据我在网上的搜索情况,这一块一直是一个盲点。虽然也有接近的答案,并没有真正实用的,我经过几天的探索,终于摸索出一套可用的,分享给大家。

首先,定义一个类,叫calendar,这个是搬运来的。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
# -*- coding: utf-8 -*-
import calendar
import tkinter as tk
import tkinter.font as tkfont
from tkinter import ttk
datetime = calendar.datetime.datetime
timedelta = calendar.datetime.timedelta
 
class calendar:
 def __init__(s, point = none):
 s.master = tk.toplevel()
 s.master.withdraw()
 s.master.attributes('-topmost' ,true)
 fwday = calendar.sunday
 year = datetime.now().year
 month = datetime.now().month
 locale = none
 sel_bg = '#ecffc4'
 sel_fg = '#05640e'
 s._date = datetime(year, month, 1) #每月第一日
 s._selection = none   #设置为未选中日期
 s.g_frame = ttk.frame(s.master)
 s._cal = s.__get_calendar(locale, fwday)
 s.__setup_styles() # 创建自定义样式
 s.__place_widgets() # pack/grid 小部件
 s.__config_calendar() # 调整日历列和安装标记
 # 配置画布和正确的绑定,以选择日期。
 s.__setup_selection(sel_bg, sel_fg)
 # 存储项id,用于稍后插入。
 s._items = [s._calendar.insert('', 'end', values='') for _ in range(6)]
 # 在当前空日历中插入日期
 s._update()
 s.g_frame.pack(expand = 1, fill = 'both')
 s.master.overrideredirect(1)
 s.master.update_idletasks()
 width, height = s.master.winfo_reqwidth(), s.master.winfo_reqheight()
 s.height=height
 if point:
 x, y = point[0], point[1]
 else:
 x, y = (s.master.winfo_screenwidth() - width)/2, (s.master.winfo_screenheight() - height)/2
 s.master.geometry('%dx%d+%d+%d' % (width, height, x, y)) #窗口位置居中
 s.master.after(300, s._main_judge)
 s.master.deiconify()
 s.master.focus_set()
 s.master.wait_window() #这里应该使用wait_window挂起窗口,如果使用mainloop,可能会导致主程序很多错误
 
 def __get_calendar(s, locale, fwday):
 if locale is none:
 return calendar.textcalendar(fwday)
 else:
 return calendar.localetextcalendar(fwday, locale)
 
 def __setitem__(s, item, value):
 if item in ('year', 'month'):
 raise attributeerror("attribute '%s' is not writeable" % item)
 elif item == 'selectbackground':
 s._canvas['background'] = value
 elif item == 'selectforeground':
 s._canvas.itemconfigure(s._canvas.text, item=value)
 else:
 s.g_frame.__setitem__(s, item, value)
 
 def __getitem__(s, item):
 if item in ('year', 'month'):
 return getattr(s._date, item)
 elif item == 'selectbackground':
 return s._canvas['background']
 elif item == 'selectforeground':
 return s._canvas.itemcget(s._canvas.text, 'fill')
 else:
 r = ttk.tclobjs_to_py({item: ttk.frame.__getitem__(s, item)})
 return r[item]
 
 def __setup_styles(s):
 # 自定义ttk风格
 style = ttk.style(s.master)
 arrow_layout = lambda dir: (
 [('button.focus', {'children': [('button.%sarrow' % dir, none)]})]
 )
 style.layout('l.tbutton', arrow_layout('left'))
 style.layout('r.tbutton', arrow_layout('right'))
 
 def __place_widgets(s):
 # 标头框架及其小部件
 input_judgment_num = s.master.register(s.input_judgment) # 需要将函数包装一下,必要的
 hframe = ttk.frame(s.g_frame)
 gframe = ttk.frame(s.g_frame)
 bframe = ttk.frame(s.g_frame)
 hframe.pack(in_=s.g_frame, side='top', pady=5, anchor='center')
 gframe.pack(in_=s.g_frame, fill=tk.x, pady=5)
 bframe.pack(in_=s.g_frame, side='bottom', pady=5)
 lbtn = ttk.button(hframe, style='l.tbutton', command=s._prev_month)
 lbtn.grid(in_=hframe, column=0, row=0, padx=12)
 rbtn = ttk.button(hframe, style='r.tbutton', command=s._next_month)
 rbtn.grid(in_=hframe, column=5, row=0, padx=12)
 s.cb_year = ttk.combobox(hframe, width = 5, values = [str(year) for year in range(datetime.now().year, datetime.now().year-11,-1)], validate = 'key', validatecommand = (input_judgment_num, '%p'))
 s.cb_year.current(0)
 s.cb_year.grid(in_=hframe, column=1, row=0)
 s.cb_year.bind('<keypress>', lambda event:s._update(event, true))
 s.cb_year.bind("<<comboboxselected>>", s._update)
 tk.label(hframe, text = '年', justify = 'left').grid(in_=hframe, column=2, row=0, padx=(0,5))
 s.cb_month = ttk.combobox(hframe, width = 3, values = ['%02d' % month for month in range(1,13)], state = 'readonly')
 s.cb_month.current(datetime.now().month - 1)
 s.cb_month.grid(in_=hframe, column=3, row=0)
 s.cb_month.bind("<<comboboxselected>>", s._update)
 tk.label(hframe, text = '月', justify = 'left').grid(in_=hframe, column=4, row=0)
 # 日历部件
 s._calendar = ttk.treeview(gframe, show='', selectmode='none', height=7)
 s._calendar.pack(expand=1, fill='both', side='bottom', padx=5)
 ttk.button(bframe, text = "确 定", width = 6, command = lambda: s._exit(true)).grid(row = 0, column = 0, sticky = 'ns', padx = 20)
 ttk.button(bframe, text = "取 消", width = 6, command = s._exit).grid(row = 0, column = 1, sticky = 'ne', padx = 20)
 tk.frame(s.g_frame, bg = '#565656').place(x = 0, y = 0, relx = 0, rely = 0, relwidth = 1, relheigh = 2/200)
 tk.frame(s.g_frame, bg = '#565656').place(x = 0, y = 0, relx = 0, rely = 198/200, relwidth = 1, relheigh = 2/200)
 tk.frame(s.g_frame, bg = '#565656').place(x = 0, y = 0, relx = 0, rely = 0, relwidth = 2/200, relheigh = 1)
 tk.frame(s.g_frame, bg = '#565656').place(x = 0, y = 0, relx = 198/200, rely = 0, relwidth = 2/200, relheigh = 1)
 
 def __config_calendar(s):
 # cols = s._cal.formatweekheader(3).split()
 cols = ['日','一','二','三','四','五','六']
 s._calendar['columns'] = cols
 s._calendar.tag_configure('header', background='grey90')
 s._calendar.insert('', 'end', values=cols, tag='header')
 # 调整其列宽
 font = tkfont.font()
 maxwidth = max(font.measure(col) for col in cols)
 for col in cols:
 s._calendar.column(col, width=maxwidth, minwidth=maxwidth,
 anchor='center')
 
 def __setup_selection(s, sel_bg, sel_fg):
 def __canvas_forget(evt):
 canvas.place_forget()
 s._selection = none
 
 s._font = tkfont.font()
 s._canvas = canvas = tk.canvas(s._calendar, background=sel_bg, borderwidth=0, highlightthickness=0)
 canvas.text = canvas.create_text(0, 0, fill=sel_fg, anchor='w')
 canvas.bind('<button-1>', __canvas_forget)
 s._calendar.bind('<configure>', __canvas_forget)
 s._calendar.bind('<button-1>', s._pressed)
 
 def _build_calendar(s):
 year, month = s._date.year, s._date.month
 header = s._cal.formatmonthname(year, month, 0)
 # 更新日历显示的日期
 cal = s._cal.monthdayscalendar(year, month)
 for indx, item in enumerate(s._items):
 week = cal[indx] if indx < len(cal) else []
 fmt_week = [('%02d' % day) if day else '' for day in week]
 s._calendar.item(item, values=fmt_week)
 
 def _show_select(s, text, bbox):
 x, y, width, height = bbox
 textw = s._font.measure(text)
 canvas = s._canvas
 canvas.configure(width = width, height = height)
 canvas.coords(canvas.text, (width - textw)/2, height / 2 - 1)
 canvas.itemconfigure(canvas.text, text=text)
 canvas.place(in_=s._calendar, x=x, y=y)
 
 def _pressed(s, evt = none, item = none, column = none, widget = none):
 """在日历的某个地方点击。"""
 if not item:
 x, y, widget = evt.x, evt.y, evt.widget
 item = widget.identify_row(y)
 column = widget.identify_column(x)
 if not column or not item in s._items:
 # 在工作日行中单击或仅在列外单击。
 return
 item_values = widget.item(item)['values']
 if not len(item_values): # 这个月的行是空的。
 return
 text = item_values[int(column[1]) - 1]
 if not text:
 return
 bbox = widget.bbox(item, column)
 if not bbox: # 日历尚不可见
 s.master.after(20, lambda : s._pressed(item = item, column = column, widget = widget))
 return
 text = '%02d' % text
 s._selection = (text, item, column)
 s._show_select(text, bbox)
 
 def _prev_month(s):
 """更新日历以显示前一个月。"""
 s._canvas.place_forget()
 s._selection = none
 s._date = s._date - timedelta(days=1)
 s._date = datetime(s._date.year, s._date.month, 1)
 s.cb_year.set(s._date.year)
 s.cb_month.set(s._date.month)
 s._update()
 
 def _next_month(s):
 """更新日历以显示下一个月。"""
 s._canvas.place_forget()
 s._selection = none
 
 year, month = s._date.year, s._date.month
 s._date = s._date + timedelta(
 days=calendar.monthrange(year, month)[1] + 1)
 s._date = datetime(s._date.year, s._date.month, 1)
 s.cb_year.set(s._date.year)
 s.cb_month.set(s._date.month)
 s._update()
 
 def _update(s, event = none, key = none):
 """刷新界面"""
 if key and event.keysym != 'return': return
 year = int(s.cb_year.get())
 month = int(s.cb_month.get())
 if year == 0 or year > 9999: return
 s._canvas.place_forget()
 s._date = datetime(year, month, 1)
 s._build_calendar() # 重建日历
 if year == datetime.now().year and month == datetime.now().month:
 day = datetime.now().day
 for _item, day_list in enumerate(s._cal.monthdayscalendar(year, month)):
 if day in day_list:
  item = 'i00' + str(_item + 2)
  column = '#' + str(day_list.index(day)+1)
  s.master.after(100, lambda :s._pressed(item = item, column = column, widget = s._calendar))
 
 def _exit(s, confirm = false):
 if not confirm: s._selection = none
 s.master.destroy()
 
 def _main_judge(s):
 """判断窗口是否在最顶层"""
 try:
 if s.master.focus_displayof() == none or 'toplevel' not in str(s.master.focus_displayof()): s._exit()
 else: s.master.after(10, s._main_judge)
 except:
 s.master.after(10, s._main_judge)
 
 def selection(s):
 """返回表示当前选定日期的日期时间。"""
 if not s._selection: return none
 year, month = s._date.year, s._date.month
 return str(datetime(year, month, int(s._selection[0])))[:10]
 
 def input_judgment(s, content):
 """输入判断"""
 if content.isdigit() or content == "":
 return true
 else:
 return false

如何使用这个类呢?直接调用即可,什么参数都不用。如图

直接调用这个类,就出现了一个选择器

Python tkinter实现日期选择器

其实你也可以用参数,比如calendar(100,100),这个参数是调整选择器的坐标位置的,问题是没啥用,没有参数选择器就出现在了屏幕的正*,凑合用吧。

显然,仅仅这样是不足以实用的,于是我又封装了一个datepicker类,需要调用calendar类

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class datepicker:
 def __init__(s,window,axes): #窗口对象 坐标
 s.window=window
 s.frame=tk.frame(s.window,padx=5)
 s.frame.grid(row=axes[0],column=axes[1])
 s.start_date=tk.stringvar() #开始日期
 s.end_date=tk.stringvar() #结束日期
 s.bt1=tk.button(s.frame,text='开始',command=lambda:s.getdate('start')) #开始按钮
 s.bt1.grid(row=0,column=0)
 s.ent1=tk.entry(s.frame,textvariable=s.start_date) #开始输入框
 s.ent1.grid(row=0,column=1)
 s.bt2=tk.button(s.frame,text='结束',command=lambda:s.getdate('end'))
 s.bt2.grid(row=0,column=2)
 s.ent2=tk.entry(s.frame,textvariable=s.end_date)
 s.ent2.grid(row=0,column=3)
 
 def getdate(s,type): #获取选择的日期
 for date in [calendar().selection()]:
 if date:
 if(type=='start'): #如果是开始按钮,就赋值给开始日期
  s.start_date.set(date)
 elif(type=='end'):
  s.end_date.set(date)
#执行
if __name__ == '__main__':
 window=tk.tk()
 window.wm_attributes('-topmost',true) #窗口置顶
 tk.label(window,text='日期段一:').grid(row=0,column=0)
 obj=datepicker(window,(0,1)) #初始化类为对象
 startstamp1=obj.start_date.get() #获取开始时期
 endstamp1=obj.end_date.get()
 
 tk.label(window,text='日期段二:').grid(row=1,column=0)
 obj=datepicker(window,(1,1))
 startstamp2=obj.start_date.get()
 endstamp2=obj.end_date.get()
 window.mainloop()

执行效果如图:

Python tkinter实现日期选择器

目的是搞成一个日期段的效果。所以datepicker类里面包括了一个开始按钮,开始输入框,结束按钮,结束输入框。并把这四个

组件放在了一个frame里面。所以使用的时候,先建立一个window,然后把window以及frame的位置坐标传入datepicker类即可。比如datepicker(window,(1,1))

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/chaodaibing/article/details/107444031