当前位置: 首页 > 面试题库 >

带有ttk日历的Python tkinter

柳逸春
2023-03-14
问题内容

我正在使用此代码在Tkinter上创建一个简单的日历。当我在主根窗口上放置日历时,日历显示就很好了。因此,我决定再放一个按钮来创建一个Tkinter顶层窗口,并在顶层窗口上再放1个日历。但是这次它无法显示日历,而是给了我这个错误" TclError: can't pack .18913120 inside .18912200.18912400"。谁能解释我为什么收到此错误消息。

这是我的示例代码:

import calendar
import sys
try:
    import Tkinter
    import tkFont
except ImportError: # py3k
    import tkinter as Tkinter
    import tkinter.font as tkFont

import ttk

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)

        # 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 = tkFont.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 = 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 __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 = [('%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
        text = '%02d' % text
        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() # 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

    # 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 myfunction():
    root2=Tkinter.Toplevel(root)
    ttkcal = Calendar(root2,firstweekday=calendar.SUNDAY)
    ttkcal.pack(expand=1, fill='both')

root=Tkinter.Tk()

frame=Tkinter.Frame(root)
frame.pack(side="left")

button=Tkinter.Button(root,text="Top level",command=myfunction)
button.pack(side="right")

ttkcal = Calendar(frame,firstweekday=calendar.SUNDAY)
ttkcal.pack(expand=1, fill='both')
root.mainloop()

问题答案:

这个小部件的作者使用了一个不必要的动作:这个小部件设置了最小的 窗口大小,并且他假定它是程序中唯一的窗口(这不是bug,它是功能)。

1.In方法def __place_widgets(self)

self._calendar = ttk.Treeview(show='', selectmode='none', height=7)

应该:

self._calendar = ttk.Treeview(self, show='', selectmode='none', height=7)

2.在构造函数中删除行:

self._calendar.bind('<Map>', self.__minsize)

3.删除__minsize方法
4.如果要设置最小大小以root2使用此代码:

def myfunction():
    root2=Tkinter.Toplevel(root)
    ttkcal = Calendar(root2,firstweekday=calendar.SUNDAY)
    ttkcal.pack(expand=1, fill='both')
    root2.update()
    root2.minsize(root2.winfo_reqwidth(), root2.winfo_reqheight())


 类似资料:
  • 我有一些关于Android日历的问题。我想添加数据库上的事件。我想要的是,当我打开我的日历片段时,它将调用web service并从服务器获取数据,其中包括日期和它们各自的事件,当我在日历中单击该日期时,它将显示指定日期的事件。我面临的问题是: > 在这一行上显示了一些错误,它说 在它成功运行之前的两天,问题是它会在日历日生成两次点。示例:我的服务器响应是 所以它会指向日期13一次,而日期10那么

  • 我正在寻找在特定日期添加事件的日历视图,如下所示: 默认的日历视图可以帮助我做同样的事情,或者有任何其他的API可以帮助获得像上面这样的结果吗? 让我知道! 谢谢

  • 日历demo,可以显示阳历和阴历,显示范围是1900年到2100年。左右滑动手势切换月份,标题点击出现年份和月份选择器,“今天”按钮返回当日,每天日期均可点击(接口已经预留),“今天”的lable背景呈现黄色。 [Code4App.com]

  • 我们需要获取Office 365日历帐户中的所有日历 我们基本上对endpointhttps://graph . Microsoft . com/v 1.0/users/[log-in-user-id]/calendars进行api调用 但是当我们调用API时,它只返回10个日历(最多)!? 任何帮助/提示表示赞赏!

  • 我目前正在尝试这样做,当我在日历视图中选择一天时,该天的所有事件都会列出。我很难让它显示一天中的所有事件(看起来它在上午12点到11点59分不起作用?)。这里是我目前拥有的。 和 如果我有12am-11:59am的事件1和12pm-11:59pm的事件2,则仅列出事件2。

  • 日历组件用来选择年月日,可以代替系统原生的日历组件,提供更统一的视觉和交互以及更好的兼容性。日历组件需要初始化才能使用,最简单的方式是通过一下JS代码来初始化,绑定到一个input元素上: $("#my-input").calendar({     value: ['2015-12-05'] }); 当你点击input元素后,会自动弹出一个JS生成的日历组件。当用户选择日期之后,input的值