吾爱破解 - 52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 1597|回复: 14
收起左侧

[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] 纯文本查看 复制代码
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
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
pangxiaohe 发表于 2025-3-16 08:52
多谢楼主分享优秀工具
mojue 发表于 2025-3-16 09:08
感谢楼主分享的源码
gegegefei 发表于 2025-3-16 12:17
感谢楼主分享,有了这个工具,工作中更方便了。
liuyang207 发表于 2025-3-16 14:04
可以的,刚运行了一下
tasty007 发表于 2025-3-17 09:22
这小工具可以就是拿来设置闹钟的吗....
还有其他用途吗
siqi47 发表于 2025-3-17 09:28
工具不错,谢谢分享。
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

返回列表

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

GMT+8, 2025-5-25 21:26

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

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