在Python 3.5中删除Canvas(s)

时间:2016-08-09 16:14:18

标签: python canvas

我是Python的新手,现在尝试通过修改ttkcalendar模块来自学代码。基本上,我的目标是基于模块生成日程安排,允许显示事件的具体日期。因此,我创建了一个txt记录来存储数据并在加载日历时读取它们。根据数据,我通过在日历上创建一些画布来突出显示日期(通过过程:def _show_selection(self,text,bbox))。现在的问题是系统没有帮助我通过单击“上一步”或“下一步”按钮移动到另一个月时删除以前的画布。在修改代码时,原始的place_forget()语法似乎不再起作用了。我认为我的问题分为两部分:

  1. 任何方法可以帮助我指向创建的画布的完整参考?我甚至都不知道他们的完整参考!
  2. 删除/删除/销毁画布的任何方法,以便我可以在移动到另一个月时重新开始突出显示任务?
  3. 我的代码如下所示,非常感谢您的帮助。 ^。^

    """
    Simple calendar using ttk Treeview together with calendar and datetime
    classes.
    """
    import calendar
    from calendar import monthrange
    import tkinter
    import tkinter.font
    from tkinter import ttk
    from tkinter import *
    import time
    from datetime import date
    
    
    def get_calendar(locale, fwday):
        # instantiate proper calendar class
        if locale is None:
            return calendar.TextCalendar(fwday)
        else:
            return calendar.LocaleTextCalendar(fwday, locale)
    
    class Calendar(ttk.Frame):
        # XXX ToDo: cget and configure
    
        datetime = calendar.datetime.datetime
        timedelta = calendar.datetime.timedelta
    
        def __init__(self, master=None, **kw):
            """
            WIDGET-SPECIFIC OPTIONS
    
                locale, firstweekday, year, month, selectbackground,
                selectforeground
            """
            # remove custom options from kw before initializating ttk.Frame
            fwday = kw.pop('firstweekday', calendar.MONDAY)
            year = kw.pop('year', self.datetime.now().year)
            month = kw.pop('month', self.datetime.now().month)
            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)
    
            self._cal = get_calendar(locale, fwday)
    
            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()
    
            # set the minimal size for the widget
            # self._calendar.bind('<Map>', self.__minsize)
    
    
        def __setitem__(self, item, value):
               if item in ('year', 'month'):
                   raise AttributeError("attribute '%s' is not writeable" % item)
               elif item == 'selectbackground':
                   self._canvas['background'] = value
               elif item == 'selectforeground':
                   self._canvas.itemconfigure(self._canvas.text, item=value)
               else:
                   ttk.Frame.__setitem__(self, item, value)
    
        def __getitem__(self, item):
            if item in ('year', 'month'):
                return getattr(self._date, item)
            elif item == 'selectbackground':
                return self._canvas['background']
            elif item == 'selectforeground':
                return self._canvas.itemcget(self._canvas.text, 'fill')
            else:
                r = ttk.tclobjs_to_py({item: ttk.Frame.__getitem__(self, item)})
                return r[item]
    
        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
            #self._calendar = ttk.Treeview(show='', selectmode='none', height=7)
            self._calendar = ttk.Treeview(self, show='', selectmode='none', height=7)
    
            # pack the widgets
            hframe.pack(in_=self, side='top', pady=4, anchor='center')
            lbtn.grid(in_=hframe)
            self._header.grid(in_=hframe, column=1, row=0, padx=12)
            rbtn.grid(in_=hframe, column=2, row=0)
            self._calendar.pack(in_=self, expand=1, fill='both', side='bottom')
    
        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 = tkinter.font.Font()
            maxwidth = max(font.measure(col) for col in cols)
            for col in cols:
                self._calendar.column(col, width=maxwidth, minwidth=maxwidth,
                    anchor='e')
    
        def __setup_selection(self, sel_bg, sel_fg):
    
            self._font = tkinter.font.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 __minsize(self, evt):
        #    width, height = self._calendar.master.geometry().split('x')
        #    height = height[:height.index('+')]
        #    self._calendar.master.minsize(width, height)
    
        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()
    
            # 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 []
                fmt_week = [('%01d' % 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
    
            if int(text) == date.today().day:
                canvas = tkinter.Canvas(self._calendar, width = 200, height = 100,
                    background="#ecffc4", borderwidth=0, highlightthickness=0)
                canvas.text = canvas.create_text(0, 0, fill="#05640e", anchor='w',)
            else:
                canvas = tkinter.Canvas(self._calendar, width = 200, height = 100,
                    background="#FFE0E0", borderwidth=0, highlightthickness=0)
                canvas.text = canvas.create_text(0, 0, fill="#FF0000", anchor='w',)
    
            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)
    
    #        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)
    
    
        def _show_daybox(self, in_text):
            self.root = tkinter.Tk()
            daybox_frm = ttk.Frame(self.root)
            daybox_frm.pack(expand=True, fill='both')
            daybox_label = ttk.Label(daybox_frm, text = in_text)
            daybox_label.pack(side=TOP, anchor=W, fill=X, expand=YES)
            daybox_button = ttk.Button(daybox_frm, text='Ok')
            daybox_button.pack(side=TOP, anchor=W, fill=X, expand=YES)
    
        # 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
            text = '%01d' % text
    #        self._selection = (text, item, column)
            self._show_selection(text, bbox)
    #        self._show_daybox(str(self._date.year) + "-" + str(self._date.month) + "-" + text)
    
        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() # 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() # reconstruct calendar
    
    
        def set_day(self, day):
            w = self._calendar
            if not w.winfo_viewable():
                w.after(200, self.set_day, day)
                return
    
            text = '%01d' % day
            column = None
            for iid in self._items:
                rowvals = w.item(iid, 'values')
                try:
                    column = rowvals.index(text)
                except ValueError as err:
                    pass
                else:
                    item = iid
                    bbox = w.bbox(iid, column)
                    break
    
            if column is not None:
                self._selection = (text, item, column)
                self._show_selection(text, bbox)             
    
        # 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():
        import sys
        root = tkinter.Tk()
        root.title('Ttk Calendar')
        ttkcal = Calendar(firstweekday=calendar.SUNDAY)
        ttkcal.pack(expand=1, fill='both')
    
        if 'win' not in sys.platform:
            style = ttk.Style()
            style.theme_use('clam')
    
        # import the selected dates from records
    
        (_ , cur_month) = monthrange(date.today().year , date.today().month)
        for j in range(0 , CalRds.__len__()):
            Rd_date, Rd_name = CalRds[j].split(',')    
            Rd_yr, Rd_mth, Rd_day = Rd_date.split('-')    
            if (int(Rd_yr) == ttkcal._date.year) and (int(Rd_mth) == ttkcal._date.month):
                for k in range (0, cur_month + 1):
                    if int(Rd_day) == k:
                        ttkcal.set_day(k)
                        break
    
        ttkcal.set_day(date.today().day[enter image description here][1]) #    
        root.mainloop()
    
    
    if __name__ == '__main__':
        """Reading the records file"""
    
        in_f = open('CalRds.txt', 'r+')
        CalRds = in_f.read().split("\n")    
        ## 0 for date
        ## 1 for Name
    
    
        """Loading the calendar"""
        test()
    

1 个答案:

答案 0 :(得分:0)

您无需删除画布。只需创建另一个画布并将其网格化在前一个画布上,并使用相同的尺寸并在同一行和列上。