1. 程式人生 > 程式設計 >Python製作簡易版小工具之計算天數的實現思路

Python製作簡易版小工具之計算天數的實現思路

需求

給定一個日期,格式如 “2020-2-12”,計算出這個日期是 2020 年的第幾天?

實現思路

  1. 使用 tkinter 和 tkinter.ttk 對介面進行佈置;
  2. 使用 calendar 計算天數;
  3. 規範輸入日期的格式;
  4. 對月份,天數進行邏輯判斷;
  5. 輸入錯誤丟擲異常提示。

程式碼實現

# -*- coding: utf-8 -*-
'''
@File: calc_day_v2.py
@Time: 2020/02/12 20:33:22
@Author: 大夢三千秋
@Contact: [email protected]
'''
# Put the import lib here
from tkinter import *
import tkinter.messagebox as messagebox
from tkinter import ttk
import calendar
class MyException(BaseException):
  '''自定義異常類
  '''
  def __init__(self,message):
    self.message = message
def calculate(*args):
  '''計算天數方法
  '''
  try:
    # 用以儲存天數
    nums = 0
    # 獲取輸入框中的資料
    year,month,day = [int(elem) for elem in date.get().split('-')]
    # 判斷月份,規定在 1-12 之間
    if 1 <= month <= 12:
      # 遍歷計算天數
      for month_x in range(1,month + 1):
        # 計算每月的天數
        _,month_day = calendar.monthrange(year,month_x)
        # 遍歷的月份等於當前月份,對天數進行規整
        if month_x == month:
          # 文字輸入框給出的天數不符合,則丟擲異常
          if day > month_day:
            raise MyException("資訊輸入錯誤,注意天數!")
          continue
        nums += month_day
      nums += day
      # 設定值到文字框
      days.set(nums)
      the_year.set(year)
    else: # 月份超出範圍丟擲異常
      raise MyException("資訊輸入錯誤,注意月份!")
  except MyException as e:
    messagebox.showinfo(title="輸入資訊錯誤",message=e)
  except Exception as e:
    # print(e)
    messagebox.showinfo(title="輸入資訊錯誤",message="輸出格式錯誤,按照 2020-2-12 這樣的格式輸入。注意月份,天數!")
root = Tk()
root.title("計算天數")
# 設定框架
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))
# 標籤及按鈕的佈置
ttk.Label(mainframe,text="例如:2020-2-12").grid(column=5,E))
ttk.Label(mainframe,textvariable=days).grid(column=4,row=2,textvariable=the_year).grid(column=2,E))
ttk.Button(mainframe,text="Calculate",command=calculate).grid(column=5,row=3)
ttk.Label(mainframe,text="日期:").grid(column=1,sticky=E)
ttk.Label(mainframe,text="這一天是").grid(column=1,text="年的第").grid(column=3,text="天").grid(column=5,sticky=W)
# 設定內邊距
for child in mainframe.winfo_children():
  child.grid_configure(padx=5,pady=5)
date_entry.focus()
root.bind('<Return>',calculate)
root.mainloop()

使用效果

正確輸入的效果如下:

Python製作簡易版小工具之計算天數的實現思路

未按照格式輸入,錯誤提示效果:

Python製作簡易版小工具之計算天數的實現思路

月份輸入錯誤,提示效果如下:

Python製作簡易版小工具之計算天數的實現思路

天數超出當月範圍的錯誤提示效果:

Python製作簡易版小工具之計算天數的實現思路

本篇的內容主要是對昨天的 tkinter 模組的延展使用,實現一個計算天數的小工具。

以上所述是小編給大家介紹的Python製作簡易版小工具之計算天數的實現思路,希望對大家有所幫助!