[Python-checkins] r64276 - sandbox/trunk/ttk-gsoc/samples/ttkcalendar.py
guilherme.polo
python-checkins at python.org
Sat Jun 14 14:42:28 CEST 2008
Author: guilherme.polo
Date: Sat Jun 14 14:42:28 2008
New Revision: 64276
Log:
Typo fix;
New options supported: selectbackground, selectforeground;
Some janitor work;
Added support for date selection via mouse click;
Modified:
sandbox/trunk/ttk-gsoc/samples/ttkcalendar.py
Modified: sandbox/trunk/ttk-gsoc/samples/ttkcalendar.py
==============================================================================
--- sandbox/trunk/ttk-gsoc/samples/ttkcalendar.py (original)
+++ sandbox/trunk/ttk-gsoc/samples/ttkcalendar.py Sat Jun 14 14:42:28 2008
@@ -1,7 +1,7 @@
"""Simple calendar using ttk Treeview together with calendar and datetime
classes.
-wrriten by Guilherme Polo, 2008.
+written by Guilherme Polo, 2008.
"""
import calendar
@@ -15,6 +15,8 @@
import ttk
class Calendar(ttk.Frame):
+ # XXX ToDo: critical: __getitem__, cget and configure
+
datetime = calendar.datetime.datetime
timedelta = calendar.datetime.timedelta
@@ -22,47 +24,67 @@
"""
WIDGET-SPECIFIC OPTIONS
- locale, firstweekday, year, month
+ locale, firstweekday, year, month, selectbackground,
+ selectforeground
"""
# remove custom options from kw before initializating ttk.Frame
- self._fwday = kw.pop('firstweekday', 0)
+ fwday = kw.pop('firstweekday', calendar.MONDAY)
year = kw.pop('year', self.datetime.now().year)
month = kw.pop('month', self.datetime.now().month)
- self._date = self.datetime(year, month, 1)
locale = kw.pop('locale', None)
+ sel_bg = kw.pop('selectbackground', '#ecffc4')
+ sel_fg = kw.pop('selectforeground', '#05640e')
+
+ self._date = self.datetime(year, month, 1)
+ self._selection = None # no date selected
ttk.Frame.__init__(self, master, **kw)
+ # instantiate proper calendar class
if locale is None:
- self._cal = calendar.TextCalendar(self._fwday)
+ self._cal = calendar.TextCalendar(fwday)
else:
- self._cal = calendar.LocaleTextCalendar(self._fwday, locale)
+ self._cal = calendar.LocaleTextCalendar(fwday, locale)
- # custom ttk Buttons
- style = ttk.Style(master)
- style.layout('L.TButton', [('Button.leftarrow', None)])
- style.layout('R.TButton', [('Button.rightarrow', None)])
+ self.__setup_styles() # creates custom styles
+ self.__place_widgets() # pack/grid used widgets
+ self.__config_calendar() # adjust calendar columns and setup tags
+ # configure a canvas, and proper bindings, for selecting dates
+ self.__setup_selection(sel_bg, sel_fg)
+ # store items ids, used for insertion later
+ self._items = [self._calendar.insert('', 'end', values='')
+ for _ in range(6)]
+ # insert dates in the currently empty calendar
+ self._build_calendar()
+
+ def __setup_selection(self, sel_bg, sel_fg):
+ self._font = tkFont.Font()
+ self._canvas = canvas = Tkinter.Canvas(self._calendar,
+ background=sel_bg, borderwidth=0, highlightthickness=0)
+ canvas.text = canvas.create_text(0, 0, fill=sel_fg, anchor='w')
+
+ canvas.bind('<ButtonPress-1>', lambda evt: canvas.place_forget())
+ self._calendar.bind('<Configure>', lambda evt: canvas.place_forget())
+ self._calendar.bind('<ButtonPress-1>', self._pressed)
+
+ def __setup_styles(self):
+ # custom ttk styles
+ style = ttk.Style(self.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(self):
# header frame and its widgets
hframe = ttk.Frame(self)
lbtn = ttk.Button(hframe, style='L.TButton', command=self._prev_month)
rbtn = ttk.Button(hframe, style='R.TButton', command=self._next_month)
self._header = ttk.Label(hframe, width=15, anchor='center')
-
# the calendar
- cols = self._cal.formatweekheader(3).split()
- self._calendar = ttk.Treeview(show='', columns=cols, selectmode='none',
- height=7)
- self._calendar.tag_configure('header', background='grey90')
- self._calendar.insert('', 'end', values=cols, tag='header')
- # adjust columns width
- font = tkFont.Font()
- maxwidth = max(font.measure(col) for col in cols)
- for col in cols:
- self._calendar.column(col, width=maxwidth, anchor='e')
- # store treeview's tags
- self._items = [self._calendar.insert('', 'end', values='')
- for _ in range(6)]
+ self._calendar = ttk.Treeview(show='', selectmode='none', height=7)
# pack the widgets
hframe.pack(in_=self, side='top', pady=4, anchor='center')
@@ -71,43 +93,108 @@
rbtn.grid(in_=hframe, column=2, row=0)
self._calendar.pack(in_=self, expand=1, fill='both', side='bottom')
- # finally build the calendar display
- self.__build_calendar()
+ def __config_calendar(self):
+ cols = self._cal.formatweekheader(3).split()
+ self._calendar['columns'] = cols
+ self._calendar.tag_configure('header', background='grey90')
+ self._calendar.insert('', 'end', values=cols, tag='header')
+ # adjust its columns width
+ font = tkFont.Font()
+ maxwidth = max(font.measure(col) for col in cols)
+ for col in cols:
+ self._calendar.column(col, width=maxwidth, anchor='e')
- def __build_calendar(self):
+ def _build_calendar(self):
year, month = self._date.year, self._date.month
+ # update header text (Month, YEAR)
header = self._cal.formatmonthname(year, month, 0)
self._header['text'] = header.title()
- #cal = self._cal.monthdatescalendar(year, month)
- cal = self._cal.monthdayscalendar(year, month)
+ # update calendar shown dates
+ cal = self._cal.monthdayscalendar(year, month)
for indx, item in enumerate(self._items):
week = cal[indx] if indx < len(cal) else []
- #y = ['%02d' % dtime.day for dtime in week]
- y = [('%02d' % day) if day else '' for day in week]
- self._calendar.item(self._items[indx], values=y)
+ fmt_week = [('%02d' % day) if day else '' for day in week]
+ self._calendar.item(item, values=fmt_week)
+
+ def _show_selection(self, text, bbox):
+ """Configure canvas for a new selection."""
+ x, y, width, height = bbox
+
+ textw = self._font.measure(text)
+
+ canvas = self._canvas
+ canvas.configure(width=width, height=height)
+ canvas.coords(canvas.text, width - textw, height / 2 - 1)
+ canvas.itemconfigure(canvas.text, text=text)
+ canvas.place(in_=self._calendar, x=x, y=y)
+
+ # Callbacks
+
+ def _pressed(self, evt):
+ """Clicked somewhere in the calendar."""
+ 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 self._items:
+ # clicked in the weekdays row or just outside the columns
+ return
+
+ item_values = widget.item(item)['values']
+ if not len(item_values): # row is empty for this month
+ return
+
+ text = item_values[int(column[1]) - 1]
+ if not text: # date is empty
+ return
+
+ bbox = widget.bbox(item, column)
+ if not bbox: # calendar not visible yet
+ return
+
+ # update and then show selection
+ self._selection = (text, item, column)
+ self._show_selection(text, bbox)
def _prev_month(self):
+ """Updated calendar to show the previous month."""
+ self._canvas.place_forget()
+
self._date = self._date - self.timedelta(days=1)
self._date = self.datetime(self._date.year, self._date.month, 1)
- self.__build_calendar()
+ self._build_calendar() # reconstuct calendar
def _next_month(self):
+ """Update calendar to show the next month."""
+ self._canvas.place_forget()
+
year, month = self._date.year, self._date.month
self._date = self._date + self.timedelta(
days=calendar.monthrange(year, month)[1] + 1)
self._date = self.datetime(self._date.year, self._date.month, 1)
- self.__build_calendar()
+ self._build_calendar() # reconstruct calendar
+
+ # Properties
+
+ @property
+ def selection(self):
+ """Return a datetime representing the current selected date."""
+ if not self._selection:
+ return None
+
+ year, month = self._date.year, self._date.month
+ return self.datetime(year, month, int(self._selection[0]))
def test():
root = Tkinter.Tk()
root.title('Ttk Calendar')
- x = Calendar(firstweekday=6)#, locale=('pt_BR', 'UTF-8'))
- x.pack(expand=1, fill='both')
- s = ttk.Style()
- s.theme_use('clam')
+ ttkcal = Calendar(firstweekday=calendar.SUNDAY)
+ ttkcal.pack(expand=1, fill='both')
+ style = ttk.Style()
+ style.theme_use('clam')
root.mainloop()
if __name__ == '__main__':
More information about the Python-checkins
mailing list