自学内容网 自学内容网

(社恐福音)用python写一个定时弹窗功能

背景

背景是换了一个工作,需要点外卖了
写代码太认真的时候又经常忘记
这时候就需要一个闹钟
手机闹钟声音太大
会影响他人
所以用python 写一个弹窗功能,只影响自己

效果图

界面效果图
添加闹钟

弹窗效果图(带音乐)

原理

管理列表和定时功能通过windows自带的计划完成
python程序不用占用后台

源码

管理界面

import tkinter as tk
from tkinter import ttk, simpledialog
import subprocess
import sys
from pathlib import Path


def resource_path(relative_path):
    """ Get absolute path to resource, works for dev and for PyInstaller """

    base_path = Path.cwd()

    return base_path.joinpath(relative_path)

class CreateTaskDialog(simpledialog.Dialog):
    def body(self, master):
        self.task_name = tk.StringVar()
        self.head = tk.StringVar()
        self.message = tk.StringVar()
        self.time = tk.StringVar()

        tk.Label(master, text="闹钟名:").grid(row=0, sticky=tk.W)
        tk.Entry(master, textvariable=self.task_name).grid(row=0, column=1)

        tk.Label(master, text="标题:").grid(row=1, sticky=tk.W)
        tk.Entry(master, textvariable=self.head).grid(row=1, column=1)

        tk.Label(master, text="内容:").grid(row=3, sticky=tk.W)
        tk.Entry(master, textvariable=self.message).grid(row=3, column=1)

        tk.Label(master, text="时间(例如: 08:00):").grid(row=4, sticky=tk.W)
        tk.Entry(master, textvariable=self.time).grid(row=4, column=1)

        return master

    def apply(self):
        self.result = (self.task_name.get(), self.head.get(), self.message.get(), self.time.get())


def get_task_list():
    """获取任务列表"""
    
    cmd = ['schtasks', '/query', '/fo', 'csv', '/v']
    output = subprocess.check_output(cmd, text=True)
    lines = output.split(",")
    tasks = []
    for i in range(len(lines)):
            # 判断是否包含字符串"闹钟_"

            if "闹钟_" in lines[i]:
                tasks.append(lines[i].replace('\\', '').replace('"', ''))
    print(tasks)
    return tasks

def delete_selected_task():
    """删除选中的任务"""
    selected_task = task_listbox.get(tk.ACTIVE)
    task_name = selected_task.strip() # 提取任务名称
    cmd = ['schtasks', '/delete', '/tn', task_name, '/f']
    try:
        subprocess.run(cmd, check=True)
        print(f"Task '{task_name}' deleted successfully.")
        refresh_task_list()  # 刷新任务列表
    except subprocess.CalledProcessError as e:
        print(f"Failed to delete task: {e}")

def create_task():
    """创建新任务"""
    dialog = CreateTaskDialog(root)
    if dialog.result:
        task_name, head, message,  time = dialog.result
        task_name = '闹钟_' + task_name
        command = str(resource_path("run.bat ")) + head + " " + message 
        if not task_name or not time:
            tk.messagebox.showerror("Error", "Task name and time cannot be empty.")
        else:
            cmd = cmd = [
                'schtasks',
                '/create',
                '/tn', task_name,
                '/tr', command,
                '/sc', 'DAILY',
                '/mo', '1',
                '/st', time,
                '/f'
            ]
            try:
                subprocess.run(cmd, check=True)
                print(f"Task '{task_name}' created successfully.")
                refresh_task_list()  # 刷新任务列表
            except subprocess.CalledProcessError as e:
                print(f"Failed to create task: {e}")

def refresh_task_list():
    """刷新任务列表"""
    task_listbox.delete(0, tk.END)
    for task in get_task_list():
        task_listbox.insert(tk.END, task)

def main():
    print(resource_path("run.bat "))
    global root, task_listbox

    root = tk.Tk()
    root.title("闹钟列表")

    # 创建任务列表框
    task_listbox = tk.Listbox(root, width=80)
    task_listbox.pack(pady=20)

    # 刷新任务列表
    refresh_task_list()

    # 创建按钮
    delete_button = ttk.Button(root, text="删除所选闹钟", command=delete_selected_task)
    delete_button.pack(side=tk.LEFT, padx=10, pady=10)

    create_button = ttk.Button(root, text="创建新闹钟", command=create_task)
    create_button.pack(side=tk.RIGHT, padx=10, pady=10)

    refresh_button = ttk.Button(root, text="刷新列表", command=refresh_task_list)
    refresh_button.pack(side=tk.BOTTOM, padx=10, pady=10)

    root.mainloop()

if __name__ == "__main__":
    main()

弹窗运行脚本(run.bat)

@echo off
chcp 65001 > nul
cd /d "%~dp0"
C:/Users/test/AppData/Local/Programs/Python/Python312/python.exe 弹窗.py %1 %2

弹窗

import tkinter as tk
import pygame
import sys
import time
import random

def play_background_music(music_file):
    pygame.mixer.music.load(music_file)
    pygame.mixer.music.play(loops=-1)  # 循环播放

def stop_music():
    pygame.mixer.music.stop()

def shake_window(window, duration=1, intensity=10):
    start_time = time.time()
    while time.time() - start_time < duration:
        x = window.winfo_x() + random.randint(-intensity, intensity)
        y = window.winfo_y() + random.randint(-intensity, intensity)
        window.geometry('+{}+{}'.format(x, y))
        window.update_idletasks()
        time.sleep(0.01)
def on_window_appear():
    shake_window(root)

def update_time_label(label):
    current_time = time.strftime("%H:%M:%S", time.localtime())
    label.config(text=current_time)
    label.after(1000, lambda: update_time_label(label))  # 每秒更新一次

def main():

    # 检查是否有足够的参数传递
    if len(sys.argv) < 2:
        print("Usage: python script_name.py arg1 arg2 ...")
        sys.exit(1)
    argv= sys.argv

    global root
    
    pygame.init()
    pygame.mixer.init()
    
    # 假设你的音乐文件名为 'background_music.mp3'
    music_file =  '默认.mp3'
    
    play_background_music(music_file)
    
    root = tk.Tk()
    root.title(argv[1])

    root.geometry("250x100+500+200")

    
    
    label = tk.Label(root, text=argv[2])
    label.pack(pady=20)

    # 创建一个显示时间的标签
    time_label = tk.Label(root, font=("Arial", 16), fg="red")
    time_label.pack(expand=True)

    # 更新时间显示
    update_time_label(time_label)
    
    # 在窗口出现时触发抖动效果
    root.after(100, on_window_appear)

    root.mainloop()
        
    
    
   

if __name__ == "__main__":
    main()

文件目录

在这里插入图片描述

后续优化

1、可以考虑选中闹钟然后查看详情
2、可以添加闹钟类型、每周一次、每月一次、每年一次


原文地址:https://blog.csdn.net/qq_40088207/article/details/140527711

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!