当我们长期在电脑面前坐太久后,会产生一系列健康风险,包括干眼症,颈椎,腰椎,肌肉僵硬等等。解决方案是在一定的时间间隔内我们需要have a break, 远眺可以缓解干眼症等眼部症状,站起来走动两步,或者做一些舒展动作,可以让我们身体肌肉放松。Microsoft Store的一些第三方免费定时提醒程序,如BreakTimer, 常常难以在约定的时间内唤起。其他一些有着类似功能且有更丰富特性的第三方程序需要注册缴费才能使用很多功能。这触发了我自己写一个程序来实现该功能。
因为Python的功能强大,且开发程序的门槛低,所以我选择它,我电脑安装的版本是3.10. 第一步,开发一个可以显示在底部工具栏右边隐藏托盘的图标,当我们有鼠标放上去时,可以显示当前离下一次休息还剩下的时间,以分钟和秒计。点击鼠标右键时,可以弹出菜单显示当前剩余时间和退出按钮。
要实现以上功能,需要安装第三方库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 Tim