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

python 的 calendar 模块日历小程序

off999 2024-11-21 19:14 21 浏览 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()


相关推荐

阿里云国际站ECS:阿里云ECS如何提高网站的访问速度?

TG:@yunlaoda360引言:速度即体验,速度即业务在当今数字化的世界中,网站的访问速度已成为决定用户体验、用户留存乃至业务转化率的关键因素。页面加载每延迟一秒,都可能导致用户流失和收入损失。对...

高流量大并发Linux TCP性能调优_linux 高并发网络编程

其实主要是手里面的跑openvpn服务器。因为并没有明文禁p2p(哎……想想那么多流量好像不跑点p2p也跑不完),所以造成有的时候如果有比较多人跑BT的话,会造成VPN速度急剧下降。本文所面对的情况为...

性能测试100集(12)性能指标资源使用率

在性能测试中,资源使用率是评估系统硬件效率的关键指标,主要包括以下四类:#性能测试##性能压测策略##软件测试#1.CPU使用率定义:CPU处理任务的时间占比,计算公式为1-空闲时间/总...

Linux 服务器常见的性能调优_linux高性能服务端编程

一、Linux服务器性能调优第一步——先搞懂“看什么”很多人刚接触Linux性能调优时,总想着直接改配置,其实第一步该是“看清楚问题”。就像医生看病要先听诊,调优前得先知道服务器“哪里...

Nginx性能优化实战:手把手教你提升10倍性能!

关注△mikechen△,十余年BAT架构经验倾囊相授!Nginx是大型架构而核心,下面我重点详解Nginx性能@mikechen文章来源:mikechen.cc1.worker_processe...

高并发场景下,Spring Cloud Gateway如何抗住百万QPS?

关注△mikechen△,十余年BAT架构经验倾囊相授!大家好,我是mikechen。高并发场景下网关作为流量的入口非常重要,下面我重点详解SpringCloudGateway如何抗住百万性能@m...

Kubernetes 高并发处理实战(可落地案例 + 源码)

目标场景:对外提供HTTPAPI的微服务在短时间内收到大量请求(例如每秒数千至数万RPS),要求系统可弹性扩容、限流降级、缓存减压、稳定运行并能自动恢复。总体思路(多层防护):边缘层:云LB...

高并发场景下,Nginx如何扛住千万级请求?

Nginx是大型架构的必备中间件,下面我重点详解Nginx如何实现高并发@mikechen文章来源:mikechen.cc事件驱动模型Nginx采用事件驱动模型,这是Nginx高并发性能的基石。传统...

Spring Boot+Vue全栈开发实战,中文版高清PDF资源

SpringBoot+Vue全栈开发实战,中文高清PDF资源,需要的可以私我:)SpringBoot致力于简化开发配置并为企业级开发提供一系列非业务性功能,而Vue则采用数据驱动视图的方式将程序...

Docker-基础操作_docker基础实战教程二

一、镜像1、从仓库获取镜像搜索镜像:dockersearchimage_name搜索结果过滤:是否官方:dockersearch--filter="is-offical=true...

你有空吗?跟我一起搭个服务器好不好?

来人人都是产品经理【起点学院】,BAT实战派产品总监手把手系统带你学产品、学运营。昨天闲的没事的时候,随手翻了翻写过的文章,发现一个很严重的问题。就是大多数时间我都在滔滔不绝的讲理论,却很少有涉及动手...

部署你自己的 SaaS_saas如何部署

部署你自己的VPNOpenVPN——功能齐全的开源VPN解决方案。(DigitalOcean教程)dockovpn.io—无状态OpenVPNdockerized服务器,不需要持久存储。...

Docker Compose_dockercompose安装

DockerCompose概述DockerCompose是一个用来定义和管理多容器应用的工具,通过一个docker-compose.yml文件,用YAML格式描述服务、网络、卷等内容,...

京东T7架构师推出的电子版SpringBoot,从构建小系统到架构大系统

前言:Java的各种开发框架发展了很多年,影响了一代又一代的程序员,现在无论是程序员,还是架构师,使用这些开发框架都面临着两方面的挑战。一方面是要快速开发出系统,这就要求使用的开发框架尽量简单,无论...

Kubernetes (k8s) 入门学习指南_k8s kubeproxy

Kubernetes(k8s)入门学习指南一、什么是Kubernetes?为什么需要它?Kubernetes(k8s)是一个开源的容器编排系统,用于自动化部署、扩展和管理容器化应用程序。它...

取消回复欢迎 发表评论: