基于Python實現(xiàn)Windows桌面定時提醒休息程序
當我們長期在電腦面前坐太久后,會產(chǎn)生一系列健康風險,包括干眼癥,頸椎,腰椎,肌肉僵硬等等。解決方案是在一定的時間間隔內(nèi)我們需要have a break, 遠眺可以緩解干眼癥等眼部癥狀,站起來走動兩步,或者做一些舒展動作,可以讓我們身體肌肉放松。Microsoft Store的一些第三方免費定時提醒程序,如BreakTimer, 常常難以在約定的時間內(nèi)喚起。其他一些有著類似功能且有更豐富特性的第三方程序需要注冊繳費才能使用很多功能。這觸發(fā)了我自己寫一個程序來實現(xiàn)該功能。
因為Python的功能強大,且開發(fā)程序的門檻低,所以我選擇它,我電腦安裝的版本是3.10. 第一步,開發(fā)一個可以顯示在底部工具欄右邊隱藏托盤的圖標,當我們有鼠標放上去時,可以顯示當前離下一次休息還剩下的時間,以分鐘和秒計。點擊鼠標右鍵時,可以彈出菜單顯示當前剩余時間和退出按鈕。
要實現(xiàn)以上功能,需要安裝第三方庫 pystray 和 pillow。代碼如下:
import threading
from pystray import Icon, MenuItem, Menu
from PIL import Image, ImageDraw
def create_image():
# Load an existing image for the tray icon
icon_path = r"C:\technical learning\Python\take-break-icon.png" # Path to your image file (e.g., .png or .ico)
return Image.open(icon_path)
def stop_program(icon, item):
# Stop the video playback and exit the program
global keep_run
icon.stop()
keep_run=False
def start_tray_icon(icon):
# Create the system tray icon with a menu
icon.run()
myicon = Icon("VideoPlayer", create_image())
# Start the tray icon in a separate thread
tray_thread = threading.Thread(target=start_tray_icon, args=[myicon],daemon=True)
tray_thread.start()
def update_tray_menu(icon):
# Update the menu with the remaining time
global time_left
#the tray menu has three items, time left, set timer, and stop
menu = Menu(
MenuItem(f"Time left: {time_left[0]} minutes {time_left[1]} seconds", lambda icon,item:None),
MenuItem('Set Timer', set_timer), # Add the new menu option here
MenuItem('Stop', action=stop_program)
)
icon.menu = menu
#the title will show when you mouse over the icon
icon.title = f"{time_left}"
首先通過已有的圖片創(chuàng)建一個Icon object,并創(chuàng)建一個線程來運行該object。因為要實時顯示剩余時間,所以有一個update函數(shù)來對Menu內(nèi)容進行更新。
第二步,實現(xiàn)每隔預設的時間, 啟動VLC播放器,播放一段指定的視頻。同時計時器重新開始倒計時。
import subprocess
import time
# Path to VLC and your video file
vlc_path = r"D:\Program Files (x86)\VideoLAN\VLC\vlc.exe" # Update if needed
video_path = r"C:\technical learning\Python\Health_song_Fxx.mp4"
#the minutes and seconds to pass to have a break periodically,default is 60 minutes
time_set = (59,60)
# Global variable to track time left
time_left = list(time_set)
keep_run = True
def start_play_video():
subprocess.run([vlc_path, video_path])
while keep_run:
update_tray_menu(myicon) #you can see the update of time_left instantly
if time_left[0]==-1: #it's the time for a break
video_play_thread = threading.Thread(target=start_play_video)
video_play_thread.start()
time_left = list(time_set) # Reset time left
time.sleep(1)
if time_left[1]==0:
time_left[1]=60
time_left[0]-=1
time_left[1] -= 1
主線程是一個while loop,每隔1s更新time_left,當time out,啟動一個線程來通過subprocess來調(diào)用VLC播放器來播放視頻,之所以用subprocess是這樣一般可以帶來前臺窗體播放的效果,更好的提醒作用。當Icon點擊了stop后,keep_run為False,循環(huán)退出,程序結(jié)束。
最簡單功能的桌面定時提醒程序這時候可以告一段落了,但是在你使用電腦的過程中,你可能本身會中途離開,比方說中午午餐,去開會,或者去做運動了。這時候電腦進入休眠狀態(tài)。當你回來后,計時器還是會按照計算機休眠前剩余的時間繼續(xù)計時,這個不太合理。因為這個時候你其實已經(jīng)眼睛和身體已經(jīng)得到了一些放松,起碼沒有一直盯著屏幕。所以應該重新開始計時。
要實現(xiàn)Windows計算機從休眠中醒來重新計數(shù),需要安裝第三方庫pywin32,別被名字糊弄,因為歷史原因,它后續(xù)的版本也包括了64 bit windows.
import win32api
import win32gui
import win32con
#the class used to handle event of computer waking up from hibernation
class PowerEventHandler:
def __init__(self):
self.internal_variable = 0
def handle_event(self, hwnd, msg, wparam, lparam):
global time_left
if msg == win32con.WM_POWERBROADCAST and wparam == win32con.PBT_APMRESUMEAUTOMATIC:
#print("Laptop woke up from hibernation!")
time_left = [59,60]
list(time_set)
return True
'''creates a custom Windows Message Handling Window'''
handler = PowerEventHandler()
wc = win32gui.WNDCLASS()
wc.lpszClassName = 'PowerHandler'
wc.hInstance = win32api.GetModuleHandle(None)
wc.lpfnWndProc = handler.handle_event
class_atom = win32gui.RegisterClass(wc)
#create a window of the registered class with no size and invisible
hwnd = win32gui.CreateWindow(class_atom, 'PowerHandler', 0, 0, 0, 0, 0, 0, 0, wc.hInstance, None)創(chuàng)建一個不可見窗體來接受Windows系統(tǒng)的消息,當接收到從休眠中醒來的消息時,重置剩下的時間為預設值。同時你需要在while loop里不斷地處理pending的Windows系統(tǒng)消息。
win32gui.PumpWaitingMessages()
第四步,目前為止,隔多少時間休息的時間段是在程序里寫死的,默認是60分鐘。用戶可能需要根據(jù)自己的偏好進行修改。那么需要在Icon的Menu里增加一個選項,點擊后彈框進行時間段設置。
這里就要用到tkinter lib,這個默認在Pythond的安裝包里,無需另外安裝。
import tkinter as tk
from tkinter import simpledialog
#a pop up dialog to set the time_set
def set_timer(icon, item):
#after the user clicking the set button
def validate_and_set_time():
nonlocal root, error_label
try:
minutes = int(minute_input.get())
seconds = int(second_input.get())
#print(minutes,seconds)
# Validate range [0, 60]
if 0 <= minutes <= 60 and 0 <= seconds <= 60:
with time_left_lock:
global time_set,time_left
time_set=(minutes,seconds)
time_left=list(time_set) #each time_set is set, time_let needs to update accordingly
#print(time_left)
root.destroy() # Close dialog if input is valid
else:
error_label.config(text="Minutes and seconds must be between 0 and 60!")
except ValueError:
error_label.config(text="Please enter valid integers!")
#create the dialog
root = tk.Tk()
root.title("Set Timer")
root.geometry("300x200")
# Get screen width and height
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
# Calculate position x and y to center the window
window_width = 300
window_height = 200
position_x = (screen_width // 2) - (window_width // 2)
position_y = (screen_height // 2) - (window_height // 2)
# Set the geometry to center the window
root.geometry(f"{window_width}x{window_height}+{position_x}+{position_y}")
tk.Label(root, text="Set Timer").pack(pady=5)
tk.Label(root, text="Minutes (0-60):").pack()
minute_input = tk.Entry(root)
minute_input.pack()
tk.Label(root, text="Seconds (0-60):").pack()
second_input = tk.Entry(root)
second_input.pack()
error_label = tk.Label(root, text="", fg="red") # Label for error messages
error_label.pack(pady=5)
#set the button call-back method to validate_and_set_time
tk.Button(root, text="Set", command=validate_and_set_time).pack(pady=10)
root.mainloop()上面的代碼就包括了彈窗設計,用戶輸入數(shù)據(jù)校驗,間隔時間段設置,以及剩余時間重置等。
另外,在Icon的Menu里需增加一欄,用于設置間隔時間段。
MenuItem('Set Timer', set_timer), # Add the new menu option here
最后一步,為了讓用戶設置的時間段間隔永久生效,需要用一個文件來存儲。 啟動這個程序的時候,從這個文件讀數(shù)據(jù),退出程序的時候,把數(shù)據(jù)存入到該文件。
這是鼠標移到Icon上,點擊右鍵出現(xiàn)的Menu:

下面是點擊Set Timer后的彈框。

到此這篇關于基于Python實現(xiàn)Windows桌面定時提醒休息程序的文章就介紹到這了,更多相關Python定時提醒內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
python3 requests庫實現(xiàn)多圖片爬取教程
今天小編就為大家分享一篇python3 requests庫實現(xiàn)多圖片爬取教程,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-12-12

