Python 简易版小工具 | 计算天数
生活随笔
收集整理的這篇文章主要介紹了
Python 简易版小工具 | 计算天数
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
文章目錄
- 簡(jiǎn)易版小工具 | 計(jì)算天數(shù)
- 需求
- 實(shí)現(xiàn)思路
- 代碼實(shí)現(xiàn)
- 使用效果
簡(jiǎn)易版小工具 | 計(jì)算天數(shù)
需求
給定一個(gè)日期,格式如 “2020-2-12”,計(jì)算出這個(gè)日期是 2020 年的第幾天?
實(shí)現(xiàn)思路
代碼實(shí)現(xiàn)
# -*- coding: utf-8 -*- ''' @File: calc_day_v2.py @Time: 2020/02/12 20:33:22 @Author: 大夢(mèng)三千秋 @Contact: yiluolion@126.com '''# Put the import lib here from tkinter import * import tkinter.messagebox as messagebox from tkinter import ttk import calendarclass MyException(BaseException):'''自定義異常類'''def __init__(self, message):self.message = messagedef calculate(*args):'''計(jì)算天數(shù)方法'''try:# 用以存儲(chǔ)天數(shù)nums = 0# 獲取輸入框中的數(shù)據(jù)year, month, day = [int(elem) for elem in date.get().split('-')]# 判斷月份,規(guī)定在 1-12 之間if 1 <= month <= 12:# 遍歷計(jì)算天數(shù)for month_x in range(1, month + 1):# 計(jì)算每月的天數(shù)_, month_day = calendar.monthrange(year, month_x)# 遍歷的月份等于當(dāng)前月份,對(duì)天數(shù)進(jìn)行規(guī)整if month_x == month:# 文本輸入框給出的天數(shù)不符合,則拋出異常if day > month_day:raise MyException("信息輸入錯(cuò)誤,注意天數(shù)!")continuenums += month_daynums += day# 設(shè)置值到文本框days.set(nums)the_year.set(year)else: # 月份超出范圍拋出異常raise MyException("信息輸入錯(cuò)誤,注意月份!")except MyException as e:messagebox.showinfo(title="輸入信息錯(cuò)誤", message=e)except Exception as e:# print(e)messagebox.showinfo(title="輸入信息錯(cuò)誤", message="輸出格式錯(cuò)誤,按照 2020-2-12 這樣的格式輸入。注意月份,天數(shù)!")root = Tk() root.title("計(jì)算天數(shù)")# 設(shè)置框架 mainframe = ttk.Frame(root, padding="3 3 12 12") mainframe.grid(column=0, row=0, sticky=(N, S, E, W)) root.columnconfigure(0, weight=1) root.rowconfigure(0, weight=1)date = StringVar() the_year = StringVar() days = StringVar()# 文本框部件布置 date_entry = ttk.Entry(mainframe, width=10, textvariable=date) date_entry.grid(column=2, row=1, sticky=(W, E))# 標(biāo)簽及按鈕的布置 ttk.Label(mainframe, text="例如:2020-2-12").grid(column=5, row=1, sticky=(W, E)) ttk.Label(mainframe, textvariable=days).grid(column=4, row=2, sticky=(W, E)) ttk.Label(mainframe, textvariable=the_year).grid(column=2, row=2, sticky=(W, E)) ttk.Button(mainframe, text="Calculate", command=calculate).grid(column=5, row=3)ttk.Label(mainframe, text="日期:").grid(column=1, row=1, sticky=E) ttk.Label(mainframe, text="這一天是").grid(column=1, row=2, sticky=E) ttk.Label(mainframe, text="年的第").grid(column=3, row=2, sticky=E) ttk.Label(mainframe, text="天").grid(column=5, row=2, sticky=W)# 設(shè)置內(nèi)邊距 for child in mainframe.winfo_children():child.grid_configure(padx=5, pady=5)date_entry.focus()root.bind('<Return>', calculate)root.mainloop()
使用效果
正確輸入的效果如下:
未按照格式輸入,錯(cuò)誤提示效果:
月份輸入錯(cuò)誤,提示效果如下:
天數(shù)超出當(dāng)月范圍的錯(cuò)誤提示效果:
本篇的內(nèi)容主要是對(duì)昨天的 tkinter 模塊的延展使用,實(shí)現(xiàn)一個(gè)計(jì)算天數(shù)的小工具。
歡迎搜索關(guān)注微信公眾號(hào)《書所集錄》
總結(jié)
以上是生活随笔為你收集整理的Python 简易版小工具 | 计算天数的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: matlab guide图像处理实例,现
- 下一篇: dhcp协议服务器怎么设置,DHCP服务