吾爱破解 - 52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 2909|回复: 9
收起左侧

[Python 原创] 智能时间工具 1.0 源码开放

  [复制链接]
byl1214 发表于 2025-3-15 22:52
该工具需要python环境下运行!!!
若没有进行如下操作:
安装Python(已安装可跳过)
  • 访问官网 www.python.org
  • 点击黄色按钮下载最新版
  • 安装时务必勾选 Add Python to PATH(重要!)

声明:
1.该工具写于python 3.13 64-bit
2.工具功能微小,有兴趣者自行添加调配
使用方法:

1.win+r,输入cmd,再输入pip install playsound pywin32 ntplib 安装工具
2.然后就可以使用了,可以添加闹钟,设置音乐等功能了
3.闹钟输入格式为:xx:xx

效果图:
qq_pic_merged_1742046095200.jpg
源码:
[Python] 纯文本查看 复制代码
import tkinter as tk
from tkinter import messagebox, filedialog
import datetime
import threading
import time
import os
import sys
import platform
from playsound import playsound
import ntplib
import socket

# ======================
# 时间同步模块
# ======================
def sync_time():
    """自动同步网络时间"""
    try:
        client = ntplib.NTPClient()
        response = client.request('pool.ntp.org')
        network_time = datetime.datetime.fromtimestamp(response.tx_time)
        
        # 仅适用于Windows
        if platform.system() == 'Windows':
            os.system(f'date {network_time:%Y-%m-%d}')
            os.system(f'time {network_time:%H:%M:%S}')
        # 适用于Linux/macOS
        else:
            os.system(f'sudo date -s "{network_time}"')
            
    except (ntplib.NTPException, socket.error):
        return False
    return True

# ======================
# 闹钟管理器
# ======================
class AlarmManager:
    def __init__(self):
        self.alarms = []
        self.running = True
        self.thread = threading.Thread(target=self._check_alarms)
        self.thread.daemon = True
        self.thread.start()

    def _check_alarms(self):
        while self.running:
            now = datetime.datetime.now().strftime("%H:%M")
            for alarm in self.alarms[:]:
                if alarm['time'] == now and not alarm['triggered']:
                    alarm['triggered'] = True
                    self._trigger_alarm(alarm)
            time.sleep(10)

    def _trigger_alarm(self, alarm):
        if alarm['sound']:
            threading.Thread(target=playsound, args=(alarm['sound'],)).start()
        messagebox.showinfo("闹钟提醒", f"时间到!{alarm['time']}")

    def add_alarm(self, time_str, sound=None):
        self.alarms.append({
            'time': time_str,
            'sound': sound,
            'triggered': False
        })

    def remove_alarm(self, index):
        if 0 <= index < len(self.alarms):
            del self.alarms[index]

# ======================
# GUI界面
# ======================
class ClockApp(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("智能时钟工具")
        self.geometry("400x300")
        self.alarm_manager = AlarmManager()
        
        # 时间显示
        self.time_label = tk.Label(self, font=('Arial', 40))
        self.time_label.pack(pady=20)
        
        # 日期显示
        self.date_label = tk.Label(self, font=('Arial', 20))
        self.date_label.pack()
        
        # 闹钟列表
        self.alarm_listbox = tk.Listbox(self, width=30)
        self.alarm_listbox.pack(pady=10)
        
        # 添加控件
        btn_frame = tk.Frame(self)
        btn_frame.pack(pady=10)
        
        self.time_entry = tk.Entry(btn_frame, width=10)
        self.time_entry.pack(side=tk.LEFT, padx=5)
        
        tk.Button(btn_frame, text="添加闹钟", command=self.add_alarm).pack(side=tk.LEFT, padx=5)
        tk.Button(btn_frame, text="删除闹钟", command=self.remove_alarm).pack(side=tk.LEFT, padx=5)
        tk.Button(btn_frame, text="选择音乐", command=self.select_music).pack(side=tk.LEFT, padx=5)
        
        self.music_file = None
        self.update_time()
        
        # 窗口置顶
        self.attributes('-topmost', True)
        
    def update_time(self):
        now = datetime.datetime.now()
        self.time_label.config(text=now.strftime("%H:%M:%S"))
        self.date_label.config(text=now.strftime("%Y-%m-%d %A"))
        self.after(1000, self.update_time)
        
    def add_alarm(self):
        time_str = self.time_entry.get()
        try:
            datetime.datetime.strptime(time_str, "%H:%M")
            self.alarm_manager.add_alarm(time_str, self.music_file)
            self.alarm_listbox.insert(tk.END, f"{time_str} - {os.path.basename(self.music_file) if self.music_file else '无音乐'}")
        except ValueError:
            messagebox.showerror("错误", "时间格式应为 HH:MM")
            
    def remove_alarm(self):
        selection = self.alarm_listbox.curselection()
        if selection:
            index = selection[0]
            self.alarm_manager.remove_alarm(index)
            self.alarm_listbox.delete(index)
            
    def select_music(self):
        self.music_file = filedialog.askopenfilename(
            filetypes=[("音频文件", "*.mp3 *.wav")]
        )

# ======================
# 开机自启设置
# ======================
def set_autostart(enable=True):
    system = platform.system()
    
    if system == "Windows":
        import winreg
        key = winreg.HKEY_CURRENT_USER
        path = r"Software\Microsoft\Windows\CurrentVersion\Run"
        try:
            with winreg.OpenKey(key, path, 0, winreg.KEY_WRITE) as regkey:
                if enable:
                    exe_path = os.path.abspath(sys.argv[0])
                    winreg.SetValueEx(regkey, "SmartClock", 0, winreg.REG_SZ, exe_path)
                else:
                    winreg.DeleteValue(regkey, "SmartClock")
        except WindowsError:
            pass
            
    elif system == "Linux":
        autostart_dir = os.path.expanduser("~/.config/autostart")
        desktop_file = os.path.join(autostart_dir, "smartclock.desktop")
        
        if enable:
            if not os.path.exists(autostart_dir):
                os.makedirs(autostart_dir)
                
            with open(desktop_file, "w") as f:
                f.write(f"""[Desktop Entry]
Type=Application
Exec=python3 {os.path.abspath(sys.argv[0])}
Hidden=false
Name=SmartClock
Comment=智能时钟工具""")
        else:
            if os.path.exists(desktop_file):
                os.remove(desktop_file)

# ======================
# 主程序
# ======================
if __name__ == "__main__":
    # 首次运行时同步时间
    if not sync_time():
        messagebox.showwarning("警告", "网络时间同步失败,使用本地时间")
        
    # 设置开机自启(需要管理员权限)
    try:
        set_autostart(enable=True)
    except PermissionError:
        messagebox.showwarning("警告", "需要管理员权限设置开机自启")
        
    # 启动GUI
    app = ClockApp()
    app.mainloop()

免费评分

参与人数 6吾爱币 +12 热心值 +3 收起 理由
moonmandog + 1 谢谢@Thanks!
xyufrk + 1 + 1 谢谢分享
HoanMeirin + 1 谢谢@Thanks!
苏紫方璇 + 7 + 1 欢迎分析讨论交流,吾爱破解论坛有你更精彩!
grrr_zhao + 1 + 1 谢谢@Thanks!
ma4907758 + 1 谢谢@Thanks!

查看全部评分

发帖前要善用【论坛搜索】功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

那些年打的飞机 发表于 2025-3-16 07:47
多谢楼主分享优秀工具
mhdythaha 发表于 2025-3-16 08:14
co2qy 发表于 2025-3-16 08:42
头像被屏蔽
liuyang207 发表于 2025-3-16 14:04
提示: 作者被禁止或删除 内容自动屏蔽
tasty007 发表于 2025-3-17 09:22
这小工具可以就是拿来设置闹钟的吗....
还有其他用途吗
xuexihtri 发表于 2025-3-17 21:04
谢谢分享
DDS5205201 发表于 2025-3-18 20:36
感谢分享方便了好多
LQ789 发表于 2025-3-19 18:49
感谢楼主,学习使用
youkui31 发表于 2025-3-30 22:20
没明白是什么意思
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

返回列表

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - 52pojie.cn ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2026-10-22 19:34

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表