Kalenderpicker in Python tkinter
Ein Experiment ...
Code: Alles auswählen
''' tk_date_picker102.py
modified:
http://www.python-forum.org/viewtopic.php?f=12&t=5104
'''
import calendar
import datetime as dt
try:
# Python2
import Tkinter as tk
except ImportError:
# Python3
import tkinter as tk
class Calendar:
def __init__(self, parent):
self.parent = parent
self.cal = calendar.TextCalendar(calendar.SUNDAY)
self.year = dt.datetime.now().year
self.month = dt.datetime.now().month
self.wid = []
self.selected = 'test'
self.setup(self.year, self.month)
def clear(self):
for w in self.wid[:]:
w.grid_forget()
self.wid.remove(w)
def go_prev(self):
if self.month > 1:
self.month -= 1
else:
self.month = 12
self.year -= 1
self.clear()
self.setup(self.year, self.month)
def go_next(self):
if self.month < 12:
self.month += 1
else:
self.month = 1
self.year += 1
self.clear()
self.setup(self.year, self.month)
def selection(self, day):
self.day = day
year = self.year
month = self.month
wdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
wday = wdays[dt.date.weekday(dt.date(year, month, day))]
date = "{} {}/{}/{}".format(wday, month, day, year)
self.sel_label["text"] = date
self.selected = date
#print(date) # test
#self.parent.update()
def setup(self, y, m):
left = tk.Button(self.parent, text='<', command=self.go_prev)
self.wid.append(left)
left.grid(row=0, column=1)
header = tk.Label(self.parent, height=2,
text='{} {}'.format(calendar.month_abbr[m], str(y)))
self.wid.append(header)
header.grid(row=0, column=2, columnspan=3)
right = tk.Button(self.parent, text='>', command=self.go_next)
self.wid.append(right)
right.grid(row=0, column=5)
days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
for num, name in enumerate(days):
t = tk.Label(self.parent, text=name)
self.wid.append(t)
t.grid(row=1, column=num)
for w, week in enumerate(self.cal.monthdayscalendar(y, m), 2):
for d, day in enumerate(week):
if day != 0:
b = tk.Button(self.parent, width=2,
text=day,
command=lambda day=day: self.selection(day))
self.wid.append(b)
b.grid(row=w, column=d)
self.sel_label = tk.Label(self.parent, height=2, width=12)
self.wid.append(self.sel_label)
self.sel_label.grid(row=8, column=1, columnspan=3)
root = tk.Tk()
root.geometry("+{}+{}".format(100, 150))
cal = Calendar(root)
root.mainloop()
Atomkraftwerkaktienbesitzer