📌  相关文章
📜  如何在Python创建 AGE Calculator Web App PyWebIO?

📅  最后修改于: 2022-05-13 01:55:50.821000             🧑  作者: Mango

如何在Python创建 AGE Calculator Web App PyWebIO?

在本文中,我们将创建一个年龄计算器,它会借助当前日期以年、月和日为单位显示您的年龄。我们将使用 PyWebIO 模块在网络上创建一个简单的交互式界面。这是一个Python模块,主要用于使用Python编程在 Web 上创建简单的交互式界面。可以使用以下命令安装它:

pip install pywebio

分步实施:

第 1 步:导入所有必需的模块。

Python3
# Import the following modules
from dateutil.relativedelta import relativedelta
from datetime import datetime
from time import strptime
from pywebio.input import *
from pywebio.output import *
from pywebio.session import *
import time


Python3
# Getting Current time.
date = datetime.now().strftime("%d/%m/%Y")  
  
# Taking age from the user
DOB = input("", placeholder = "Your Birth Date(dd/mm/yyyy)")


Python3
try:
    # Check whether the input age format 
    # is same as given format
    val = strptime(DOB, "%d/%m/%Y")
except:
    
    # If format is different, then through 
    # an error.
    put_error("Alert! This is not the right format")
    time.sleep(3)  # sleep for 3 seconds
    continue


Python3
# Split the age by '/'
in_date = DOB.split('/')
  
# split the todays date by '/'
date = date.split('/')  
  
# Typecast all the converted part 
# into the int.
in_date = [int(i) for i in in_date] 
date = [int(i) for i in date] 
newdate = []  
  
# Swap days with years
in_date[0], in_date[2] = in_date[2], in_date[0]  
  
# Swap days with years
date[0], date[2] = date[2], date[0]


Python3
if in_date <= date:
        now = datetime.strptime(DOB, "%d/%m/%Y")
      
        # Display output in a pop window
        popup("Your Age",k
              [put_html("

"f"{relativedelta(datetime.now(),now).years} Years
\               {relativedelta(datetime.now(),now).months} Months
\               {relativedelta(datetime.now(),now).days} Days""

"), put_buttons(                   ['Close'], onclick=lambda _: close_popup())], implicit_close=True) else:         # If you input the year greater than current year         put_warning(             f"No result found, this is {date[0]}, and you can't be in {in_date[0]}.")


Python3
# Import the following modules
from dateutil.relativedelta import relativedelta
from datetime import datetime
from time import strptime
from pywebio.input import *
from pywebio.output import *
from pywebio.session import *
import time
  
# Run infinite loop
while True:  
    clear() 
      
    # Put a heading Age Calculator
    put_html("

AGE CALCULATOR

")            # Getting Current time.     date = datetime.now().strftime("%d/%m/%Y")              # Taking age from the user     DOB = input("", placeholder="Your Birth Date(dd/mm/yyyy)")     try:                  # Check whether the input age         # format is same as given format         val = strptime(DOB, "%d/%m/%Y")     except:                  # If format is different, then through an error.         put_error("Alert! This is not the right format")                    # sleep for 3 seconds         time.sleep(3)           continue     in_date = DOB.split('/')      date = date.split('/')              # Typecast all the converted part into the int.     in_date = [int(i) for i in in_date]     date = [int(i) for i in date]            # Define an empty list     newdate = []              # Swap days with years     in_date[0], in_date[2] = in_date[2], in_date[0]              # Swap days with years     date[0], date[2] = date[2], date[0]       if in_date <= date:         now = datetime.strptime(DOB, "%d/%m/%Y")                    # Display output         popup("Your Age",               [put_html("

"f"{relativedelta(datetime.now(),now).years} Years
\               {relativedelta(datetime.now(),now).months} Months
\               {relativedelta(datetime.now(),now).days} Days""

"), put_buttons(                   ['Close'], onclick=lambda _: close_popup())], implicit_close=True)     else:                  # If you input the year greater than current year         put_warning(             f"No result found, this is {date[0]}, and you can't be in {in_date[0]}.")         time.sleep(3)     clear()     # Give user a choice     choice = radio("Do you want to calculate again?",                    options=['Yes', 'No'], required=True)     if choice.lower() == 'yes':         continue     else:         clear()                    # Show a toast notification         toast("Thanks a lot!")           exit()


第 2 步:获取当前时间并接受用户的输入。



蟒蛇3

# Getting Current time.
date = datetime.now().strftime("%d/%m/%Y")  
  
# Taking age from the user
DOB = input("", placeholder = "Your Birth Date(dd/mm/yyyy)")

第三步:检查年龄格式是否正确。

蟒蛇3

try:
    # Check whether the input age format 
    # is same as given format
    val = strptime(DOB, "%d/%m/%Y")
except:
    
    # If format is different, then through 
    # an error.
    put_error("Alert! This is not the right format")
    time.sleep(3)  # sleep for 3 seconds
    continue

第 4 步:将用户的出生日期和当前日期按“/”拆分。然后将所有拆分的部分 Typecast 为整数。交换用户的出生日期和当前日期的月份和年份。

蟒蛇3

# Split the age by '/'
in_date = DOB.split('/')
  
# split the todays date by '/'
date = date.split('/')  
  
# Typecast all the converted part 
# into the int.
in_date = [int(i) for i in in_date] 
date = [int(i) for i in date] 
newdate = []  
  
# Swap days with years
in_date[0], in_date[2] = in_date[2], in_date[0]  
  
# Swap days with years
date[0], date[2] = date[2], date[0]

步骤5:检查当前年份是否小于用户的DOB 年份。如果当前年份小于通过错误。

蟒蛇3

if in_date <= date:
        now = datetime.strptime(DOB, "%d/%m/%Y")
      
        # Display output in a pop window
        popup("Your Age",k
              [put_html("

"f"{relativedelta(datetime.now(),now).years} Years
\               {relativedelta(datetime.now(),now).months} Months
\               {relativedelta(datetime.now(),now).days} Days""

"), put_buttons(                   ['Close'], onclick=lambda _: close_popup())], implicit_close=True) else:         # If you input the year greater than current year         put_warning(             f"No result found, this is {date[0]}, and you can't be in {in_date[0]}.")

完整代码:

蟒蛇3

# Import the following modules
from dateutil.relativedelta import relativedelta
from datetime import datetime
from time import strptime
from pywebio.input import *
from pywebio.output import *
from pywebio.session import *
import time
  
# Run infinite loop
while True:  
    clear() 
      
    # Put a heading Age Calculator
    put_html("

AGE CALCULATOR

")            # Getting Current time.     date = datetime.now().strftime("%d/%m/%Y")              # Taking age from the user     DOB = input("", placeholder="Your Birth Date(dd/mm/yyyy)")     try:                  # Check whether the input age         # format is same as given format         val = strptime(DOB, "%d/%m/%Y")     except:                  # If format is different, then through an error.         put_error("Alert! This is not the right format")                    # sleep for 3 seconds         time.sleep(3)           continue     in_date = DOB.split('/')      date = date.split('/')              # Typecast all the converted part into the int.     in_date = [int(i) for i in in_date]     date = [int(i) for i in date]            # Define an empty list     newdate = []              # Swap days with years     in_date[0], in_date[2] = in_date[2], in_date[0]              # Swap days with years     date[0], date[2] = date[2], date[0]       if in_date <= date:         now = datetime.strptime(DOB, "%d/%m/%Y")                    # Display output         popup("Your Age",               [put_html("

"f"{relativedelta(datetime.now(),now).years} Years
\               {relativedelta(datetime.now(),now).months} Months
\               {relativedelta(datetime.now(),now).days} Days""

"), put_buttons(                   ['Close'], onclick=lambda _: close_popup())], implicit_close=True)     else:                  # If you input the year greater than current year         put_warning(             f"No result found, this is {date[0]}, and you can't be in {in_date[0]}.")         time.sleep(3)     clear()     # Give user a choice     choice = radio("Do you want to calculate again?",                    options=['Yes', 'No'], required=True)     if choice.lower() == 'yes':         continue     else:         clear()                    # Show a toast notification         toast("Thanks a lot!")           exit()

输出: