百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术资源 > 正文

python 的 calendar 模块日历小程序

off999 2024-11-21 19:14 14 浏览 0 评论

用python的calendar模块写一个日历小程序,其中有时钟,还可以上下查看每个月,每天可以写备注(记事),同时实现窗口中的日期控件跟随窗口的大小变化,同时变大变小

第一个是时钟功能;

时钟功能就是简单的导入time模块,调用系统当前时间,再用 after(1000,function) 来实现1秒更新,再把结果显示到 label中就即可

def Clock(self):
        # 用来显示时间标签
        self.timeframe = LabelFrame(self,text='Time:',bg='gray',fg='white')
        self.timeframe.place(x=10,y=10)
        self.timelabel = Label(self.timeframe,bg='gray',width=15,font=('',12,'bold'),fg='white')
        self.timelabel.pack()

    def update(self):
        # 用来更新显示时间
        self.timelabel.config(text=time.strftime("%H : %M : %S"))  # 更新时间标签的内容
        self.after(1000,self.update)   # 间隔 1000 毫秒,调用函数

第二个是选择年月功能,通过time模块的 localtime().tm_year 与 localtime().tm_mon方法可以获取当前的年、月,calendar模块中的monthcalenndar方法也需要年,月这两个参数,所以这里就可以通过更新年份和月份来更新日历,需要注意的是1月和12月变化要调用 adjustment()方法来实现

def select_date(self): # 显示顶部 xxxx年 xx 月的标签
        for widget in self.winfo_children():
            widget.destroy()

        self.dateframe = Frame(self)
        self.dateframe.pack(anchor='center',pady=10)
        self.up_label = Label(self.dateframe, text='<', font=('', 14), width=3, height=2)
        self.up_label.pack(side='left', padx=10)
        self.up_label.bind("<1>", lambda event: self.adjustment('up'))  # 这里绑定一下单击事件,触发时月份 -1
        datavar = StringVar()
        datavar.set(str(self.year) + ' 年 ' + str(self.month) + ' 月')
        self.calenderlabel = Label(self.dateframe, textvariable=datavar)
        self.calenderlabel.pack(side='left', padx=10)
        self.down_label = Label(self.dateframe, text='>', font=('', 14), width=3, height=2)
        self.down_label.pack(side='left', padx=10)
        self.down_label.bind("<1>", lambda event: self.adjustment('down')) # 这里绑定一下单击事件,触发时月份 +1

    def adjustment(self,Side): # 该方法用来判定月份为1、12时,被调用时年份与月份的值
        if Side == 'up':
            self.month -=1
            if self.month == 0:
                self.year -= 1
                self.month = 12
        elif Side == 'down':
            self.month += 1
            if self.month == 13:
                self.year += 1
                self.month = 1
        self.select_date()
        self.Clock()
        self.setUI()
        self.myplace()
        self.bind('<Configure>', self.window_resize)

第三个是备注功能:

每个日期做为一个 Key存到字典中,如果有输入备注,更新这个Key的内容,通过label显示内容

def diary(self,event,Num):  # 用于显示日期内容
        for widget in self.content_cv.winfo_children():
            if self.button == widget:
                widget.destroy()
        if Num == 1:
            for day in self.day_label_list:
                if day['text']==event.widget['text']:
                    self.content_label.config(text='{}年{}月{}日'.format(self.year, self.month, day['text']))
            self.day_content.config(text=self.data_dict[event.widget['text']],anchor='w')
            if self.first_text == True:
                self.text.destroy()
                self.first_text = False
            else:
                self.first_text = False
                return
        elif Num == 2:
            if self.first_text == False:
                self.text = Text(self.content_cv)
                self.text.place(x=15, y=45, relwidth=0.56, relheight=0.6)
                self.button = Button(self.content_cv, text='确 认')
                self.button.place(relx=0.75, rely=0.5, relwidth=0.1)
                self.button.config(command=lambda: self.change_text(event.widget))
                self.first_text = True
            else:
                self.first_text = False
                return

    def change_text(self,event):  # 用于更新日期备注
        for item in self.data_dict:
            if self.data_dict[item] == event['text']:
                if self.text.get(1.0,'end-1c') == '':   # 获取所有文本,但不包括最后的换行符
                    self.data_dict[item] = event['text']
                    event.config(text=self.data_dict[item])
                else:
                    self.data_dict[item] = self.text.get(1.0,'end')
                    event.config(text=self.data_dict[item])
        self.text.destroy()
        self.button.destroy()

第四 个是窗口属性(configure):

这里就是把所有需要变化的控件都使用place()方法实例化,因为 place 方法中有 relwidth(父容器宽的百分比为宽),relheight(父容器高的百分比为高),再把这些控件的 place() 放到一个函数(myplace() )中,在每一次主窗口属性变化时,调用该函数,最后就是一个绑定窗口件事的方法 **bind('<Configure>', self.window_resize)**

def setUI(self):  # 设置日历主体
        self.cv = Canvas(self,bg='snow',bd=1,relief='solid')
        self.bind('<Configure>', self.window_resize)
        # 设置星期标签
        weekdays = ['一', '二', '三', '四', '五', '六', '日']
        self.week_label = []
        for i, item in enumerate(weekdays): # 创建星期标签,并加入到标签列表中
            self.label = Label(self.cv, text=item, font=self.myfont, width=3, height=2)
            self.label.place(relx=0.15 + i / 10, rely=0.04, relwidth=0.1, relheight=0.1)
            self.week_label.append(self.label)
        # 设置日期标签
        self.day_label_list = []   # 用于保存生成日期的标签(对象)
        for j, week in enumerate(calendar.monthcalendar(self.year, self.month)): # 通过模块获取日历,返回一个矩阵
            for index, day in enumerate(week):
                if day == 0:
                    continue
                self.day_label = Label(
                    self.cv, text=day,
                    font=self.myfont,
                    anchor='nw',
                    bd=1,
                    relief='solid',
                )
                self.day_label.place(relx=0.15 + index / 10, rely=0.17 + j / 6, relwidth=0.09, relheight=0.15)

                # 标签绑定单击事件
                self.day_label.bind("<Button-1>", lambda event, Num=1: self.diary(event, Num))

                # 定位系统当天日期
                if self.year == time.localtime().tm_year and self.month == time.localtime().tm_mon and day == time.localtime().tm_mday:
                    self.day_label.config(bg='lightblue', fg='red')

                # 把生成的日期标签添加到列表中
                self.day_label_list.append(self.day_label)
                self.data_dict[day] = '{}年{}月{}日'.format(self.year, self.month, day)

        self.content_cv = Canvas(self,bg='snow',bd=1,relief='solid')
        self.content_label = Label(self.content_cv,text='日期')
        self.day_content = Label(self.content_cv,text='')
        self.text = Text(self.content_cv)
        self.button = Button(self.content_cv,text='确 认')

    def myplace(self):
        self.cv.place(x=10,y=60,widt=self.width-20,height=self.height//1.6)

        self.myfont = ('楷体', self.width//40)   # 重置星期的字休,大小
        for label in self.week_label:
            label.config(font=self.myfont)

        self.myfont = ('楷体', self.width // 60)  # 重置日期字体,大小
        for day_label in self.day_label_list:
            day_label.config(font=self.myfont)

        self.content_cv.place(x=10,rely=0.73,widt=self.width-20,relheight=0.25)
        self.content_label.place(x=15,y=15,relwidth=0.2,relheight=0.15)
        self.day_content.place(x=15,y=45,relwidth=0.96,relheight=0.6)
        self.day_content.bind('<Double-1>',lambda event,bool=2:self.diary(event,bool))

    # 窗口重置
    def window_resize(self,event=None):
        if event:
            if self.winfo_width() == self.width and self.winfo_height() == self.height:
                return
            if self.first_load:
                self.first_load = False
                return
            self.width = self.winfo_width()
            self.height = self.winfo_height()
            self.myplace()

全部代码


from tkinter import *
import calendar
import time

class time_calender(Tk):
    def __init__(self):
        super(time_calender, self).__init__()
        self.first_load =True
        self.first_text = True
        self.labelNum = None
        self.data_dict = {}
        self.width = 600
        self.height = 600
        self.minsize(self.width,self.height)   # 设置窗口最小尺寸
        self.geometry('{}x{}'.format(self.width, self.height))   # 设置窗口初始尺寸
        self.year = time.localtime().tm_year   # 获取当前系统时间的年份
        self.month = time.localtime().tm_mon    # 获取当前系统时间的月份
        self.day = time.localtime().tm_mday     # 获取当前系统时间的日期
        self.select_date()
        self.Clock()
        self.update()
        self.myfont = ('楷体', 10)
        self.setUI()
        self.myplace()
        self.bind('<Configure>', self.window_resize) # 绑定窗口属性事件,当窗口发生变化时执行

    def Clock(self):
        # 用来显示时间标签
        self.timeframe = LabelFrame(self,text='Time:',bg='gray',fg='white')
        self.timeframe.place(x=10,y=10)
        self.timelabel = Label(self.timeframe,bg='gray',width=15,font=('',12,'bold'),fg='white')
        self.timelabel.pack()

    def update(self):
        # 用来更新显示时间
        self.timelabel.config(text=time.strftime("%H : %M : %S"))  # 更新时间标签的内容
        self.after(1000,self.update)   # 间隔 1000 毫秒,调用函数

    def select_date(self): # 显示顶部 xxxx年 xx 月的标签
        for widget in self.winfo_children():
            widget.destroy()

        self.dateframe = Frame(self)
        self.dateframe.pack(anchor='center',pady=10)
        self.up_label = Label(self.dateframe, text='<', font=('', 14), width=3, height=2)
        self.up_label.pack(side='left', padx=10)
        self.up_label.bind("<1>", lambda event: self.adjustment('up'))  # 这里绑定一下单击事件,触发时月份 -1
        datavar = StringVar()
        datavar.set(str(self.year) + ' 年 ' + str(self.month) + ' 月')
        self.calenderlabel = Label(self.dateframe, textvariable=datavar)
        self.calenderlabel.pack(side='left', padx=10)
        self.down_label = Label(self.dateframe, text='>', font=('', 14), width=3, height=2)
        self.down_label.pack(side='left', padx=10)
        self.down_label.bind("<1>", lambda event: self.adjustment('down')) # 这里绑定一下单击事件,触发时月份 +1

    def adjustment(self,Side): # 该方法用来判定月份为1、12时,被调用时年份与月份的值
        if Side == 'up':
            self.month -=1
            if self.month == 0:
                self.year -= 1
                self.month = 12
        elif Side == 'down':
            self.month += 1
            if self.month == 13:
                self.year += 1
                self.month = 1
        self.select_date()
        self.Clock()
        self.setUI()
        self.myplace()
        self.bind('<Configure>', self.window_resize)

    def setUI(self):  # 设置日历主体
        self.cv = Canvas(self,bg='snow',bd=1,relief='solid')
        self.bind('<Configure>', self.window_resize)
        # 设置星期标签
        weekdays = ['一', '二', '三', '四', '五', '六', '日']
        self.week_label = []
        for i, item in enumerate(weekdays): # 创建星期标签,并加入到标签列表中
            self.label = Label(self.cv, text=item, font=self.myfont, width=3, height=2)
            self.label.place(relx=0.15 + i / 10, rely=0.04, relwidth=0.1, relheight=0.1)
            self.week_label.append(self.label)
        # 设置日期标签
        self.day_label_list = []   # 用于保存生成日期的标签(对象)
        for j, week in enumerate(calendar.monthcalendar(self.year, self.month)): # 通过模块获取日历,返回一个矩阵
            for index, day in enumerate(week):
                if day == 0:
                    continue
                self.day_label = Label(
                    self.cv, text=day,
                    font=self.myfont,
                    anchor='nw',
                    bd=1,
                    relief='solid',
                )
                self.day_label.place(relx=0.15 + index / 10, rely=0.17 + j / 6, relwidth=0.09, relheight=0.15)

                # 标签绑定单击事件
                self.day_label.bind("<Button-1>", lambda event, Num=1: self.diary(event, Num))

                # 定位系统当天日期
                if self.year == time.localtime().tm_year and self.month == time.localtime().tm_mon and day == time.localtime().tm_mday:
                    self.day_label.config(bg='lightblue', fg='red')

                # 把生成的日期标签添加到列表中
                self.day_label_list.append(self.day_label)
                self.data_dict[day] = '{}年{}月{}日'.format(self.year, self.month, day)

        self.content_cv = Canvas(self,bg='snow',bd=1,relief='solid')
        self.content_label = Label(self.content_cv,text='日期')
        self.day_content = Label(self.content_cv,text='')
        self.text = Text(self.content_cv)
        self.button = Button(self.content_cv,text='确 认')

    def myplace(self):
        self.cv.place(x=10,y=60,widt=self.width-20,height=self.height//1.6)

        self.myfont = ('楷体', self.width//40)   # 重置星期的字休,大小
        for label in self.week_label:
            label.config(font=self.myfont)

        self.myfont = ('楷体', self.width // 60)  # 重置日期字体,大小
        for day_label in self.day_label_list:
            day_label.config(font=self.myfont)

        self.content_cv.place(x=10,rely=0.73,widt=self.width-20,relheight=0.25)
        self.content_label.place(x=15,y=15,relwidth=0.2,relheight=0.15)
        self.day_content.place(x=15,y=45,relwidth=0.96,relheight=0.6)
        self.day_content.bind('<Double-1>',lambda event,bool=2:self.diary(event,bool))

    # 窗口重置
    def window_resize(self,event=None):
        if event:
            if self.winfo_width() == self.width and self.winfo_height() == self.height:
                return
            if self.first_load:
                self.first_load = False
                return
            self.width = self.winfo_width()
            self.height = self.winfo_height()
            self.myplace()

    def diary(self,event,Num):  # 用于显示日期内容
        for widget in self.content_cv.winfo_children():
            if self.button == widget:
                widget.destroy()
        if Num == 1:
            for day in self.day_label_list:
                if day['text']==event.widget['text']:
                    self.content_label.config(text='{}年{}月{}日'.format(self.year, self.month, day['text']))
            self.day_content.config(text=self.data_dict[event.widget['text']],anchor='w')
            if self.first_text == True:
                self.text.destroy()
                self.first_text = False
            else:
                self.first_text = False
                return
        elif Num == 2:
            if self.first_text == False:
                self.text = Text(self.content_cv)
                self.text.place(x=15, y=45, relwidth=0.56, relheight=0.6)
                self.button = Button(self.content_cv, text='确 认')
                self.button.place(relx=0.75, rely=0.5, relwidth=0.1)
                self.button.config(command=lambda: self.change_text(event.widget))
                self.first_text = True
            else:
                self.first_text = False
                return

    def change_text(self,event):  # 用于更新日期备注
        for item in self.data_dict:
            if self.data_dict[item] == event['text']:
                if self.text.get(1.0,'end-1c') == '':   # 获取所有文本,但不包括最后的换行符
                    self.data_dict[item] = event['text']
                    event.config(text=self.data_dict[item])
                else:
                    self.data_dict[item] = self.text.get(1.0,'end')
                    event.config(text=self.data_dict[item])
        self.text.destroy()
        self.button.destroy()

if __name__ == '__main__':
    app = time_calender()
    app.mainloop()


相关推荐

python pip 命令 参数(python pip命令用不了)

usage:python[option]...[-ccmd|-mmod|file|-][arg]...Options(andcorrespondingenvironm...

Python 包管理:uv 来了!比 pip 快 100 倍的神器,开发者的终极选择?

为什么Python开发者需要uv?Python生态虽繁荣,但包管理一直是痛点:pip安装慢如蜗牛、依赖冲突让人头秃、虚拟环境配置繁琐……直到uv横空出世!这个用Rust语言打造的...

UV:Python包管理的未来已来!比pip快100倍的新选择

引言Python开发者们,是否厌倦了pip的缓慢安装速度?是否希望有一个更快、更现代、更高效的包管理工具?今天,我要向大家介绍一个革命性的Python包管理工具——UV!UV由Rust编写,是pip和...

「Python」 常用的pip命令和Django命令

pip命令如何根据关键词找到PyPI(Python包仓库)上的可用包#方法1:直接访问PyPI官网,输入关键词搜索#方法2#为何不用pipsearchdjango?因为这个命令已不可...

python包管理工具pip freeze详解(python工具包怎么用)

freeze就像其名字表示的意思一样,主要用来以requirement的格式输出已安装的包,这里我们主要讨论以下3个选项:--local、--user、--pathlocal--local选项一般用在...

python包管理工具pip config详解(python的pulp包)

pipconfig主要包含以下子命令:set、get、edit、list、debug、unset。下面我们逐一介绍下它们。pipconfigset这个命令允许我们以name=value的形式配...

pip常用命令,学Python不会这个寸步难行哦(26)

小朋友们好,大朋友们好!我是猫妹,一名爱上Python编程的小学生。欢迎和猫妹一起,趣味学Python。今日主题学习下pip的使用。pip什么是pippip全称PythonPackageIndex...

Python pip 包管理需知(python的包管理)

简介在Python编程中,pip是一个强大且广泛使用的包管理工具。它使我们能够方便地安装、升级和管理Python包。无论是使用第三方库还是分享自己的代码,pip都是我们的得力助手。本文将深入解析pip...

比pip快100倍的Python包安装工具(python如何用pip安装包)

简介uv是一款开源的Python包安装工具,GitHubstar高达56k,以性能极快著称,具有以下特性(官方英文原文):Asingletooltoreplacepip,pip-tool...

Python安装包总报错?这篇解决指南让你告别pip烦恼!

在Python开发中,pip是安装和管理第三方包的必备工具,但你是否经常遇到各种报错,比如无法创建进程、权限不足、版本冲突,甚至SSL证书错误?这些问题不仅浪费时间,还让人抓狂!别担心!本文整理了...

pip vs pipx: Python 包管理器,你选择哪个?

高效的包管理对于Python开发至关重要。pip和pipx是两个最常用的工具。虽然两者都支持安装Python包,但它们的设计和用例却大相径庭。本文将探讨这些差异,解释何时使用每种工具,并...

【python】5分钟掌握pip(包管理)操作

安装一个软件包从庞大的仓库中找到一个库,将其导入您的环境:pipinstallnumpy2.已安装软件包列表调查您领域内存在的库的概要,注意它们的版本:piplist3.升级软件包赋予已安装...

Python pip安装与使用步骤(python的pip安装方法)

安装和使用Python的包管理工具pip是管理Python包和依赖项的基础技能。以下是详细的步骤:安装pip使用系统包管理器安装Windows:通常,安装Python时会自动安装p...

Python自动化办公应用学习笔记3—— pip工具安装

3.1pip工具安装最常用且最高效的Python第三方库安装方式是采用pip工具安装。pip是Python包管理工具,提供了对Python包的查找、下载、安装、卸载的功能。pip是Python官方提...

Python文件压缩神器:ZipFile功能全解析,支持一键压缩和解压

在Python中处理ZIP文件时,zipfile模块是最常用的工具。它提供了创建、读取、修改ZIP文件的完整功能,无需依赖外部命令。本文将通过核心函数、实战案例和避坑指南,带你掌握这个高效的文件处理模...

取消回复欢迎 发表评论: