为宝贝大孙子写的成长日志记录小程序

2024年7月3日早晨06时06分,在这个温馨而充满喜悦的时刻,我们迎来了家族中最璀璨的星辰——我的宝贝孙子,一个带着无限希望与梦想降临人间的小天使。他的到来,如同春日里最温暖的阳光,瞬间融化了我们所有人的心房,让家中每一个角落都洋溢着幸福与欢笑。此刻我依然还沉寂在那幸福的一刻。于是我有了一个美好的想法,我要用自己的专长为我孙子编个记录他今后成长的日志的小程序。记录从他出生到他以后的成长岁月的点点滴滴。

设计思路及功能简介

以超文本html的格式显示输出,内容包括标题、日历插件、宝贝的一些个人信息、出生时长的实时更新时间、珍贵的拍摄照片。

日志文本是json文件格式,用单独开发的小程序进行日志记录保存、和照片上传。同样是根据日历插件进行选择并输入日志记录。

下面分享一下我的“孙子成长记录日志小程序”。

html文本的源程序如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>动态背景颜色变换与日历日志</title>
    <style>
    body {
            color: white;
            transition: background-color 2s ease-in-out;
        }

        h1 {
            font-weight: bold;
            font-family: '宋体', sans-serif;
        }
     #imageCarousel {
            width: 700px;
            height: 800px;
            position: absolute;
            top: 0px;
            right: 0px;
            overflow: hidden;
        }

        .carouselImage {
            width: 100%;
            height: 100%;
            position: absolute;
            opacity: 0;
            transition: opacity 1s;
        }
        </style>
    <style>
        body {
            color: white;
            transition: background-color 2s ease-in-out;
        }

        h1 {
            font-weight: bold;
            font-family: '宋体', sans-serif;
        }
    </style>
</head>
<body>
    宝贝大孙子的成长记录日志
    <h3>选择日期并查看当天的日志</h3>
    <input type="date" id="selectedDate">
    <button onclick="showLog()">显示日志</button>
    <p>出生日期: 2024年07月03日 <br>阴    历:二零二四年五月二十八 甲辰年 (龙年)<br>属    相: 龙<br>年    龄: 1毛岁<br>
    <p id="timeDifference"></p>
    <div id="logContent"></div>
    <script>
        // 固定时间:2024-07-03 06:06:00
        const fixedTime = new Date('2024-07-03T06:06:00').getTime();

        function updateTimeDifference() {
            const currentTime = new Date().getTime();
            const timeDiff = currentTime - fixedTime;

            const daysDiff = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
            const hoursDiff = Math.floor((timeDiff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
            const minutesDiff = Math.floor((timeDiff % (1000 * 60 * 60)) / (1000 * 60));
            const secondsDiff = Math.floor((timeDiff % (1000 * 60)) / 1000);

            document.getElementById("timeDifference").innerHTML = `今天是出生的 第${daysDiff}天 ${hoursDiff}小时 ${minutesDiff}分钟 ${secondsDiff}秒`;
        }

        // 每秒更新一次时间差
        setInterval(updateTimeDifference, 1000);
    </script>

    <script>
        function showLog() {
            const selectedDate = document.getElementById('selectedDate').value;
            const logContent = document.getElementById('logContent');

            fetch('logData.json')
                .then(response => response.json())
                .then(data => {
                    if (data[selectedDate]) {
                        logContent.innerHTML = `<h2>${selectedDate} 的日志:</h2><p>${data[selectedDate]}</p>`;
                    } else {
                        logContent.innerHTML = `<p>未找到 ${selectedDate} 的日志。</p>`;
                    }
                })
                .catch(error => console.error('错误:', error));
        }
        function changeBackgroundColor() {
            const randomColor = Math.floor(Math.random()*16777215).toString(16); // 生成随机颜色值
            document.body.style.backgroundColor = "#" + randomColor; // 设置背景颜色
        }
        setInterval(changeBackgroundColor, 2000); // 每2秒改变一次背景颜色
        imageInput.addEventListener('change', function() {
            const file = imageInput.files[0];
            const reader = new FileReader();

            reader.onload = function(e) {
                imageDisplay.innerHTML = `<img src="${e.target.result}" alt="Selected Image" style="max-width: 300px; max-height: 300px;">`;
            }

            reader.readAsDataURL(file);
        })
    </script>

     <script>

        const images = ["../images/2.jpg", "../images/1.png", "../images/3.jpg", "../images/7.png","../images/4.jpg","../images/1.png", "../images/10.jpg","../images/7-6-2.jpg","../images/9.jpg"]; // Add the paths of your images here
        let currentImageIndex = 0;

        // Function to display images in a carousel
        function displayImages() {
            const imageCarousel = document.getElementById("imageCarousel");
            imageCarousel.innerHTML = "";
            for (let i = 0; i < images.length; i++) {
                const image = document.createElement("img");
                image.src = images[i];
                image.classList.add("carouselImage");
                image.style.zIndex = i === currentImageIndex ? 1 : 0;
                imageCarousel.appendChild(image);
            }
            startCarousel();
        }

        function startCarousel() {
            const images = document.querySelectorAll(".carouselImage");
            let currentIndex = 0;
            const totalImages = images.length;

            setInterval(() => {
                images[currentIndex].style.opacity = 0;
                currentIndex = (currentIndex + 1) % totalImages;
                images[currentIndex].style.opacity = 1;
            }, 3000); // Change image every 3 seconds
        }

        window.onload = displayImages;
    </script>
    <div id="imageCarousel"></div>

</body>
</html>

运行结果如下图:

Screenshot 2024-07-07 at 10.24.21

Screenshot 2024-07-07 at 10.15.10

日志记录、图片上传程序源码如下:

import json
import os
import tkinter as tk
from tkinter import scrolledtext, filedialog
from tkcalendar import Calendar
from datetime import datetime
import shutil

# 定义读取日志文件的函数,返回字典格式的数据
def get_log_dict():
    if os.path.exists('./logData_old.json'):
        with open('./logData_old.json', 'r') as f:
            logs_dict = json.load(f)
        return logs_dict
    else:
        return {}

# 定义写入日志文件的函数
def write_json(data):
    with open('./logData.json', 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=4)
        
# 日志保存、图片上传函数
def log_json():
    log_data = get_log_dict()
    new_log = {}

    def upload_image():
        file_path = filedialog.askopenfilename()
        dest_path = filedialog.askdirectory()
        shutil.move(file_path, dest_path)
    def save_log():
        log_date = cal.get_date()
        date_obj = datetime.strptime(log_date, "%m/%d/%y")
        formatted_date = date_obj.strftime("%Y-%m-%d")
        log_entry = text.get("1.0", tk.END).strip()
        if log_entry:
            log_entry = log_entry
        new_log[formatted_date] = log_entry
        text.delete("1.0", tk.END)

    def save_and_exit():
        save_log()
        log_data.update(new_log)
        write_json(log_data)
        root.destroy()

    root = tk.Tk()
    root.title("宝贝大孙子日志记录程序")

    cal = Calendar(root, select_mode='day')
    cal.pack(pady=10)

    text = scrolledtext.ScrolledText(root, wrap=tk.WORD, width=40, height=10)
    text.pack(pady=10)

    button_frame = tk.Frame(root)
    button_frame.pack()

    upload_button = tk.Button(button_frame, text="上传图片", command=upload_image)
    upload_button.pack(side=tk.LEFT, padx=10)
    save_exit_button = tk.Button(button_frame, text="保存并退出", command=save_and_exit)
    save_exit_button.pack(side=tk.RIGHT, padx=10)

    root.mainloop()

# 主函数

if __name__ == '__main__':
    log_json()

运行结果如下:

Screenshot 2024-07-07 at 10.25.18

**备注:**部分代码由AI完成,感谢这个伟大的AI时代。