最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

基于Python實現(xiàn)Windows桌面定時提醒休息程序

 更新時間:2024年11月26日 10:04:30   作者:正義之兔  
這篇文章為大家詳細主要介紹了如何基于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ù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • Python defaultdict方法使用分析

    Python defaultdict方法使用分析

    在使用Python字典的過程中,如果沒有key就會自動報錯,這時就需要python中defaultdict函數(shù)發(fā)揮作用。defaultdict是Python內(nèi)建dict類的一個子類,功能與dict相同,但可以產(chǎn)生一個帶有默認值的dict,如果key不存在,就會返回默認值
    2022-10-10
  • Python中的int函數(shù)使用

    Python中的int函數(shù)使用

    這篇文章主要介紹了Python中的int函數(shù)使用方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-11-11
  • Python中返回函數(shù)的完全指南

    Python中返回函數(shù)的完全指南

    在Python編程中,函數(shù)不僅可以執(zhí)行操作,還可以作為返回值,這種特性為編程帶來了極大的靈活性和強大的表達能力,本文將全面介紹Python中的返回函數(shù),從基礎概念到高級應用場景,幫助開發(fā)者掌握這一重要特性,需要的朋友可以參考下
    2025-05-05
  • Python字符串中查找子串小技巧

    Python字符串中查找子串小技巧

    這篇文章主要介紹了Python字符串中查找子串小技巧,,需要的朋友可以參考下
    2015-04-04
  • 深度解析Python中的方法綁定機制

    深度解析Python中的方法綁定機制

    這篇文章主要介紹了Python的方法綁定機制,重點探討bound method的工作原理及其背后的描述符協(xié)議,文中的示例代碼講解詳細,感興趣的小伙伴可以了解下
    2026-03-03
  • Python應用開發(fā)之實現(xiàn)串口通信

    Python應用開發(fā)之實現(xiàn)串口通信

    在嵌入式開發(fā)中我們經(jīng)常會用到串口,串口通信簡單,使用起來方便,且適用場景多。本文為大家準備了Python實現(xiàn)串口通信的示例代碼,需要的可以參考一下
    2022-11-11
  • python3 requests庫實現(xiàn)多圖片爬取教程

    python3 requests庫實現(xiàn)多圖片爬取教程

    今天小編就為大家分享一篇python3 requests庫實現(xiàn)多圖片爬取教程,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-12-12
  • python機器學習darts時間序列預測和分析

    python機器學習darts時間序列預測和分析

    這篇文章主要介紹了python機器學習darts時間序列預測和分析使用實例探索,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2024-01-01
  • Python對數(shù)據(jù)庫操作

    Python對數(shù)據(jù)庫操作

    本文給大家介紹Windows、Linux下安裝MySQL-python,及安裝過程中常遇到的問題,該如何解決,非常具有參考借鑒價值,特此分享供大家參考
    2016-03-03
  • Python?爬取微博熱搜頁面

    Python?爬取微博熱搜頁面

    這篇文章主要介紹了Python?爬取微博熱搜頁面,關于Python?爬蟲,爬取網(wǎng)頁等相關內(nèi)容一般可作為小練習,下面文章Python?爬取微博熱搜頁面也如此,需要的小伙伴可以參考一下
    2022-01-01

最新評論

邵阳市| 聂拉木县| 青州市| 潮安县| 合阳县| 正安县| 唐海县| 南投市| 宁蒗| 岳池县| 西峡县| 于田县| 神农架林区| 九台市| 留坝县| 天等县| 土默特右旗| 修文县| 淄博市| 棋牌| 宝坻区| 延安市| 进贤县| 双牌县| 奉贤区| 买车| 鄂温| 突泉县| 秭归县| 若羌县| 通江县| 中卫市| 普宁市| 彰化市| 从江县| 六安市| 南木林县| 石楼县| 宁都县| 襄樊市| 大同县|