Time lock screen program, Python I wish you the principles of sudden death!

Godfrey event

November 27 during recording "chase me" Ninth programs in the current period Panelists high to suddenly slow down when running Xiang fell to the ground, the program launched the first on-site medical treatment, and urgently sent to local hospitals. After more than two hours of rescue, the hospital finally announced Godfrey sudden cardiac death .

After this unfortunate incident, the community has been closely watched. From a sorry fans, to denounce the program group, and various causes of death analysis reports, online news overwhelming. If, however, the highest death rate on the occupation, we should not be programmers do?

 

Sudden death in high-risk occupation

Sudden death overtime every year tens of thousands of programmers, but I ask my colleagues whether we are so social serious attention, but also the country has issued any relevant policies to protect such high-risk groups? nothing!!!

Tired, someone cares about you, comfort you, is your lucky.
If luck is not coming to your head, you have to learn to use his left hand warm his right hand,
you have to tell yourself, everything will be past.

Since others do not care about programmers, we can only learn self-care of. Today we use Python to help thousands of programmers away from sudden death!

Sedentary beverages

 

 

Remember the first generation of millet bracelet on sale when, out of the sedentary remind this function. " Sedentary " harm to the person, has long been recognized by the world. Specifically, what does? Sedentary be hazardous to your colon, spine, neck, heart, pancreas, hips, legs. As to the specific content, we can take a closer look down.
So much harm in the face, but often because programmers rush demand, change BUG, check the information and sit for a few hours, do not hold back the urine less than move house. (As I write this article, has been sitting in a row on the computer side for three hours ...) detailed yourself if you have had these experiences!
Well, today we use Python developed a sedentary reminder gadget , so that each programmer can reasonably rest, time to get up and move around, away from the sudden death hazard!

programming

Python how to complete the sedentary reminder function? Initially considered regular mail, or micro-channel messages, text messages and other operations. But up there time to focus on these concerns? Finally think, it is better to develop a GUI tool that allows the programmer to set a countdown, and then see the computer screen to automatically lock when forced everyone up and walk, relax. So we have the following effects:

In order to set up a comprehensive range of time, I added a way to support fractional, but also to be able to easily record screen presentation.
However, in order to avoid sudden lock screen, causing discomfort. It will give prompt pop in front of the lock screen 10 seconds. This will not be too abrupt. This idea has triggered can be a problem.

tkinter The message will block the process , the user does not click cancel the message window, can not continue. In order to enable prompt message pops up at the same time, the countdown to the countdown continues, we need to introduce threading and Toplevel module, create a child window, and wait for three seconds to destroy it.

def notice():
    message = Toplevel(root)
    message.title('提示')
    Label(message, text='主人,工作这么久了,准备休息下吧!'
          , justify=CENTER, font=("黑体", '11')).grid()
    time.sleep(3)
    message.destroy()

 

Automatic lock screen

Familiar bat script of children's shoes all know, bat has shutdown commands can be used to periodically restart, shutdown, but no lock screen. Check for a long time to no avail, and finally only reluctantly by Python ctypes calling windll module, complete lock-screen operation, the specific code as follows:

def close_windows():
    user32 = windll.LoadLibrary('user32.dll')
    user32.LockWorkStation()

Use code

# -*- coding: utf-8 -*-
# @Author   : 王翔
# @微信号   : King_Uranus
# @公众号    : 清风Python
# @GitHub   : https://github.com/BreezePython
# @Date     : 2019/11/28 23:23
# @Software : PyCharm
# @version  :Python 3.7.3
# @File     : CareForCoders.py

from tkinter import *
from tkinter.messagebox import showwarning, showinfo
import time
from ctypes import *
import threading


# tkinter GUI工具居中展示
def center_window(master, width, height):
    screenwidth = master.winfo_screenwidth()
    screenheight = master.winfo_screenheight()
    size = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2,
                            (screenheight - height) / 2)
    master.geometry(size)


# 锁定屏幕
def close_windows():
    user32 = windll.LoadLibrary('user32.dll')
    user32.LockWorkStation()


class CareForCoders:
    def user_setting(self):
        note = LabelFrame(root, text="说明", padx=10, pady=10,
                          fg="red", font=("黑体", '11'))
        note.grid(padx=10, pady=2, sticky=NSEW)
        index = Label(note, text='程序猿/媛们,久坐伤身请务必定时休息!')
        index.grid()
        lb = LabelFrame(root, text="定时设置(支持小数)", padx=10,
                        pady=10, fg="red", font=("黑体", '11'))
        lb.grid(padx=10, pady=2, sticky=NSEW)
        self.time_entry = Entry(lb)
        self.time_entry.grid(row=1, column=0)
        unit = Label(lb, text="(单位:分)")
        unit.grid(row=1, column=1, padx=5)

        self.countdown_lb = Label(text="休息倒计时:", justify=LEFT,
                                  font=("黑体", '11'))
        self.countdown_lb.grid(row=2)
        self.submit = Button(root, text="启动", width=8,
                             command=lambda: self.get_countdown(self.time_entry.get())
                             )
        self.submit.grid(row=3, column=0, pady=10)

    def get_countdown(self, countdown):
        try:
            _float_countdown = float(countdown)
            if _float_countdown <= 0:
                showwarning("提示:", message="倒计时必须为正数!")
            else:
                self.countdown_show(_float_countdown * 60)
        except ValueError:
            showwarning("提示:", message="请填写正确的倒计时!")

    def countdown_show(self, countdown_sec):
        self.time_entry.config(state=DISABLED)
        self.submit.config(state=DISABLED)
        time.sleep(1)
        self.countdown_lb.config(text="休息倒计时: %02d:%02d" %
                                      (countdown_sec // 60, countdown_sec % 60))
        root.update()
        # 为了避免突如其来的锁屏,倒计时30秒给出提示...
        if countdown_sec == 10:
            t = threading.Thread(target=self.notice)
            t.start()

        if countdown_sec < 1:
            # 启动锁屏操作
            close_windows()
            self.time_entry.config(state=NORMAL)
            self.submit.config(state=NORMAL)
            self.countdown_lb.config(text="欢迎主人回来...")
            root.update()
            return
        countdown_sec -= 1
        self.countdown_lb.after(1000, self.countdown_show(countdown_sec))

    @staticmethod
    def notice():
        # message = Toplevel(root)
        # message.title('提示')
        # Label(message, text='主人,工作这么久了,准备休息下吧!'
        #       , justify=CENTER, font=("黑体", '11')).grid()
        # time.sleep(3)
        # message.destroy()
        showinfo("提示",message='主人,工作这么久了,准备休息下吧!')


if __name__ == '__main__':
    root = Tk()
    center_window(root, 260, 200)
    root.resizable(width=False, height=False)
    root.title('久坐提醒 by:清风Python')
    Main = CareForCoders()
    Main.user_setting()
    root.mainloop()

You can go to my github download all articles Code: https://github.com/BreezePython

Since we want the benefit of thousands of programmers, so it would be best can be packaged into exe tool, easy to spread out of context!

Use the command pyinstaller -F -w -i love.ico CareForCoders.pyto package
-F packaged into a single file, -w -i cancel cmd window to add software ico icon, to see the effect it:

Guess you like

Origin www.cnblogs.com/7758520lzy/p/11982397.html