0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Python3】PC開きすぎ防止ソフトを作ってみた

Last updated at Posted at 2021-10-04

最近、PCを見続けることが多くなり、視力が悪くなったと感じた。
そのため、以下のようなPC開きすぎ防止ソフトを作った。

1.目標

PCを開いてから1時間以内にスリープする。
また、作業時間をGUI上に表示する

2.仕様

言語:Python3.9
のちにpyinstallerでexeに。
OS:Windows10

3.実装時注意点

threadingでスリープ処理と作業経過時間表示処理を分けること。

4.実装方法とコード

sleeping.py
import ctypes
import datetime
import tkinter as tk
import time
from tkinter import messagebox
import threading
import sys
from tkinter import ttk

# 初期設定
dt = datetime.datetime.now()
print("開始時間: "+str(dt.hour)+":"+str(dt.minute)+":"+str(dt.second))
funsu = 0
flag = True

# スリープ判定
def sleep_checker():
    #8時以前と22時以降の場合何もしない
    if dt.hour >= 22 or dt.hour <8:
        pass
    else:
        time.sleep(3600)
        ctypes.windll.PowrProf.SetSuspendState(0, 1, 0)
        sys.exit()

# 経過時間表示
def show_window():
    
    #GUI設定
    root = tk.Tk()
    status = tk.StringVar()
    status.set("")
    root.title("実行監視プログラム")
    root.geometry("450x180")
    work_label=tk.Label(text="作業開始から",font=('',35),wraplength=400,anchor="center")
    work_label.pack()
    status_label=tk.Label(textvariable=status,font=('',45),wraplength=400,anchor="center")
    status_label.pack()
    
    
    # ---設定項目---
    def check_time():
        global funsu,flag
        dt_now = datetime.datetime.now()
        sabun = dt_now - dt
        
        #秒数計算
        if sabun.seconds == 1:
            flag = False
        if (sabun.seconds%60) == 0 and flag == False:
            funsu = funsu+1
        else:
            pass
        
        if funsu <1:
            status.set(str(sabun.seconds)+"秒経過")
        elif funsu == 59:
            status.set("残り1分で作業を終了してください")
        elif funsu == 60:
            root.destroy()
        else:
            status.set(str(funsu)+""+str(sabun.seconds%60)+"秒経過")

        #1秒ごと繰り返し
        root.after(1000,check_time)
    check_time()
    root.mainloop()

thread1 = threading.Thread(target=sleep_checker)
thread2 = threading.Thread(target=show_window)
thread1.start()
thread2.start()
thread1.join()
thread2.join()

以下に動作時のスクリーンショットを載せる
スクリーンショット 2021-10-04 214547.png

5.考察

sleepの処理でてこずるかと思ったが案外早くできた。
スリープ後に処理が落ちていないことがあり、スリープから復帰しても再スリープするということがあった。
対策として、Pythonのプログラムを強制終了させる手段として、sys.exit()をスリープさせた後に組み込んだ。

6.参考サイト

Windowsをスリープさせる処理を参考にさせていただきました。

Pythonにおけるスレッド処理について記載されています。参考にさせていただきました。

.pyファイルの.exe化の方法についてはこちらのサイトを参考にさせていただきました。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?