用python创建一个包含事件的一个月日历

2024-04-18 13:56:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建一个一个月的日历,我可以打印出来,并交给普通人,已经有事件。在

我想做一些类似于WinCalendar所做的事情。我会用那个程序,但评论提到了粗略的DLL、注册表项和启动默认值。难道不应该有一个python库来做这件事吗?在

我可以使用matplotlib创建我想要的东西,如下所示。在

import calendar
import matplotlib.pyplot as plt

calendar.setfirstweekday(6) # Sunday is 1st day in US
w_days = 'Sun Mon Tue Wed Thu Fri Sat'.split()
m_names = '''
January February March April
May June July August
September October November December'''.split()

class MplCalendar(object):
    def __init__(self, year, month):
        self.year = year
        self.month = month
        self.cal = calendar.monthcalendar(year, month)
        # monthcalendar creates a list of lists for each week
        # Save the events data in the same format
        self.events = [[[] for day in week] for week in self.cal]

    def _monthday_to_index(self, day):
        'The index of the day in the list of lists'
        for week_n, week in enumerate(self.cal):
            try:
                i = week.index(day)
                return week_n, i
            except ValueError:
                pass
         # couldn't find the day
        raise ValueError("There aren't {} days in the month".format(day))

    def add_event(self, day, event_str):
        'insert a string into the events list for the specified day'
        week, w_day = self._monthday_to_index(day)
        self.events[week][w_day].append(event_str)

    def show(self):
        'create the calendar'
        f, axs = plt.subplots(len(self.cal), 7, sharex=True, sharey=True)
        for week, ax_row in enumerate(axs):
            for week_day, ax in enumerate(ax_row):
                ax.set_xticks([])
                ax.set_yticks([])
                if self.cal[week][week_day] != 0:
                    ax.text(.02, .98,
                            str(self.cal[week][week_day]),
                            verticalalignment='top',
                            horizontalalignment='left')
                contents = "\n".join(self.events[week][week_day])
                ax.text(.03, .85, contents,
                        verticalalignment='top',
                        horizontalalignment='left',
                        fontsize=9)

        # use the titles of the first row as the weekdays
        for n, day in enumerate(w_days):
            axs[0][n].set_title(day)

        # Place subplots in a close grid
        f.subplots_adjust(hspace=0)
        f.subplots_adjust(wspace=0)
        f.suptitle(m_names[self.month] + ' ' + str(self.year),
                   fontsize=20, fontweight='bold')
        plt.show()

然后我可以创建一个MplCalendar对象,添加事件并显示如下。在

^{pr2}$

这将生成一个类似这样的日历。在

Sample February Matplotlib Calendar

我是在重新发明轮子吗?我尝试了一堆相关的谷歌搜索,但什么也找不到。在


Tags: oftheinselfforindexdefax