python定时自动关机(有提示框)

文章介绍了作者使用Python编写的不同版本的自动关机程序,包括开机提示、鼠标键盘活动检测和定时关机功能。通过pynput库监听键盘和鼠标活动,以及定时任务实现特定时间自动关机,适用于避免长时间无人操作导致的电脑空转。
摘要由CSDN通过智能技术生成

——————————————————————————————————————

.py文件打包成.exe方法:

在powershell终端里面输入pyinstaller --noconsole ‘your_script.py’ (不用加‘’)运行后打包成在后台运行的.exe ,--noconsole是运行后不会有控制台显示

———————————————————————————————————————————

(第一版)这个是第一版的,由于本人学校的教室的电脑是用极域管理系统来控屏,所以当老师控屏的时候不会关机,(本人目前目测是因为控屏的优先级比较大,即使运行了cmd代码也不会关机)

import time
import os
from pynput import mouse,keyboard
import tkinter as tk
from tkinter import font, messagebox
import threading


# 开机运行提示
def show_custom_message_box():
    # 创建自定义的Tkinter窗口
    root = tk.Tk()
    root.withdraw()  # 隐藏主窗口
    root.overrideredirect(False)  # 移除窗口边框

    # 创建顶级窗口作为信息框
    top = tk.Toplevel(root)
    top.overrideredirect(False)  # 移除窗口边框
    top.title("自动关机小程序")

    # 设置字体
    font_size = 14  # 字体大小
    custom_font = font.Font(family='Helvetica', size=font_size, weight='bold')

    # 创建标签并设置分段文本和字体
    text = """  
    !!!这里的内容是开机提示内容!!!
    """
    label = tk.Label(top, text=text, font=custom_font, wraplength=1000, justify='left')
    label.pack(pady=30)  # pady添加垂直填充

    # 创建确定按钮
    ok_button = tk.Button(top, text="确定", command=top.destroy)
    ok_button.pack(side=tk.BOTTOM, pady=10)  # pady添加底部填充

    # 进入Tkinter的事件循环,等待用户交互
    top.mainloop()

# 在新线程中显示自定义消息框
threading.Thread(target=show_custom_message_box).start()



# 设置超时时间(秒)
timeout = 3600  # 一个小时

# 设置剩余10min提醒
time_ten = 3000 # 50分钟

# 用来定义剩余10分钟是否触发过
show_message_if = False

# 定义一个变量来跟踪是否有活动
is_active = False


# 定义一个函数,在鼠标或键盘事件触发时设置is_active为True
def on_event(event):
    global is_active
    is_active = True

def on_move(x, y):
    global is_active
    is_active = True

def on_click(x, y, button, pressed):
    global is_active
    is_active = True

def show_message():
    global show_message_if
    messagebox.showinfo("提示", "若无操作则10分钟后自动关机")


# 使用pynput监听鼠标和键盘事件
mouse_listener = mouse.Listener(on_move=on_move, on_click=on_click)
keyboard_listener = keyboard.Listener(on_press=on_event)

# 启动监听器
mouse_listener.start()
keyboard_listener.start()

# 创建提示窗口
root = tk.Tk()
root.withdraw()  # 隐藏主窗口


# 计时器
start_time = time.time()

print("程序运行中,无操作一小时后将自动关机...")

# 等待直到超时或者用户有操作
while True:
    if time.time() - start_time > time_ten and show_message_if == False:
        threading.Thread(target=show_message).start()
        show_message_if = True
    if is_active:
        # 重置计时器和状态
        print('进行了操作')
        start_time = time.time()
        is_active = False
        show_message_if = False
    elif time.time() - start_time > timeout:
        # 执行关机命令
        os.system("shutdown /s /t 1")  # Windows系统关机命令
        break
    print(f'还有{time.time()-start_time}秒')
    time.sleep(1)  # 每秒检查一次

# 监听提示窗口事件
root.mainloop()

# 停止监听器
mouse_listener.stop()
keyboard_listener.stop()

# 确保监听器不再运行
mouse_listener.join()
keyboard_listener.join()

print("程序结束")

(第二版)所以我加以修改,将其变成定时运行检测,这里设置的是晚上9点40,如有需求修改的,可以自行修改。然后电脑20分钟无操作就自动关机(这个点了,我不信还有老师控屏!)

import os
from pynput import mouse,keyboard
import tkinter as tk
from tkinter import font, messagebox
import threading
import subprocess
import platform
from datetime import datetime, time
import time

# 开机运行提示
def show_custom_message_box():
    # 创建自定义的Tkinter窗口
    root = tk.Tk()
    root.withdraw()  # 隐藏主窗口

    # 创建顶级窗口作为信息框
    top = tk.Toplevel(root)
    top.overrideredirect(True)  # 移除窗口边框
    top.title("自动关机小程序")
    top.attributes('-fullscreen', False)  # 移除全屏模式
    top.attributes('-topmost', True)  # 窗口置顶
    top.overrideredirect(False)  # 在设置属性后再关闭overrideredirect

    # 设置窗口背景色为黑色
    top.configure(bg='black')

    # 设置字体
    font_size = 18  # 字体大小
    custom_font = font.Font(family='黑体', size=font_size, weight='bold')

    # 创建标签并设置分段文本、字体和背景色
    text = """    
    你要提示的内容,开机就提示
    """


    label = tk.Label(top, text=text, font=custom_font, wraplength=1000, justify='left', bg='black',
                     fg='pink')  # 设置前景色为白色
    label.pack(pady=300)  # pady添加垂直填充

    # 创建确定按钮,并设置背景色和前景色
    ok_button = tk.Button(top, text="确定", command=top.destroy, bg='black', fg='white')
    ok_button.pack(side=tk.BOTTOM, pady=10)  # pady添加底部填充

    label.pack(pady=50, padx=10, fill='x', expand=True)

    # 进入Tkinter的事件循环,等待用户交互
    top.mainloop()

# 在新线程中显示自定义消息框
threading.Thread(target=show_custom_message_box).start()



# 设置超时时间(秒)
timeout = 1200 # 20分钟 1200

# 设置剩余10min提醒
time_ten = 600 # 10分钟 600

# 用来定义剩余10分钟是否触发过
show_message_if = False

# 定义一个变量来跟踪是否有活动
is_active = False


# 定义一个函数,在鼠标或键盘事件触发时设置is_active为True
def on_event(event):
    global is_active
    is_active = True

def on_move(x, y):
    global is_active
    is_active = True

def on_click(x, y, button, pressed):
    global is_active
    is_active = True

def show_message():
    global show_message_if
    messagebox.showinfo("提示", "若无操作则10分钟后自动关机")


# 创建提示窗口
root = tk.Tk()
root.withdraw()  # 隐藏主窗口


# 获取当前时间
now = datetime.now()
target_time = datetime.combine(now.date(), datetime.min.time().replace(hour=21, minute=40, second=0, microsecond=0))  # 21:40

while True: # 让这个一直循环直到时间到晚上9点半以后
    now = datetime.now()
    if now >= target_time:
        break
    else:
        time.sleep(1)

# 使用pynput监听鼠标和键盘事件
mouse_listener = mouse.Listener(on_move=on_move, on_click=on_click)
keyboard_listener = keyboard.Listener(on_press=on_event)

# 启动监听器
mouse_listener.start()
keyboard_listener.start()
# 计时器
start_time = time.time()

while True:
    if time.time() - start_time > time_ten and show_message_if == False:
        threading.Thread(target=show_message).start()
        show_message_if = True

    if is_active:
        # 重置计时器和状态
        start_time = time.time()
        is_active = False
        show_message_if = False

    elif time.time() - start_time > timeout:
        print(time.time() - start_time)
        # 执行关机命令
        os.system("shutdown /s /t 1")  # Windows系统关机命令

        # 处于某些原因可能没关机,所以检测每隔20分钟再关机
        timeout = 60*20
        start_time = time.time()
        continue
    time.sleep(1)  # 每秒检查一次


# # 停止监听器
# mouse_listener.stop()
# keyboard_listener.stop()
#
# # 确保监听器不再运行
# mouse_listener.join()
# keyboard_listener.join()


(第三版)应校方要求,第三版出炉,省去了麻烦的键盘和鼠标的检测,直接变成定时关机了 

import os
import tkinter as tk
from tkinter import font, messagebox
import threading

from datetime import datetime, time
import time


def show_custom_message_box():
    # 创建自定义的Tkinter窗口
    root = tk.Tk()
    root.withdraw()  # 隐藏主窗口

    # 创建顶级窗口作为信息框
    top = tk.Toplevel(root)
    top.overrideredirect(True)  # 移除窗口边框
    top.title("自动关机小程序")
    top.attributes('-fullscreen', False)  # 移除全屏模式
    top.attributes('-topmost', True)  # 窗口置顶
    top.overrideredirect(False)  # 在设置属性后再关闭overrideredirect

    # 设置窗口背景色为黑色
    top.configure(bg='black')

    # 设置字体
    font_size = 18  # 字体大小
    custom_font = font.Font(family='黑体', size=font_size, weight='bold')

    # 创建标签并设置分段文本、字体和背景色
    text = """    
填入你想让大伙知道的内容
    """

    label = tk.Label(top, text=text, font=custom_font, justify='left', bg='black',
                     fg='cyan')  # 设置前景色为白色
    label.pack(pady=500)  # pady添加垂直填充

    # 创建确定按钮,并设置背景色和前景色
    ok_button = tk.Button(top, text="确定", command=top.destroy, bg='black', fg='cyan')
    ok_button.pack(side=tk.BOTTOM, pady=10)  # pady添加底部填充

    label.pack(pady=50, padx=10, fill='x', expand=True)

    # 进入Tkinter的事件循环,等待用户交互
    top.mainloop()

def schedule_shutdown():
    # 获取当前时间
    current_time = time.localtime()
    hour = current_time.tm_hour
    minute = current_time.tm_min

    # 检查是否是预定的关机时间
    if (hour == 12 and minute == 10) or (hour == 21 and minute == 40): # 这里把时间修改就可以变成想要的时间关机了
        print("Scheduled shutdown initiated.")
        os.system("shutdown /s /t 1")  # 关机命令

    # 每隔一段时间检查一次
    time.sleep(1)  # 等待60秒
    schedule_shutdown()


if __name__ == "__main__":
    # 在新线程中显示自定义消息框
    threading.Thread(target=show_custom_message_box).start()

    # 启动定时关机任务
    schedule_shutdown()

(第五版) hhhhh,好像第四版的运行会报错,作者这边用不了,然后接下来第五版的是结合第二版的再加上一个时间点12:10分。加了个if判断,目前第五版会在12:10分和21:35分开始运行,检测是否有操作,若无则12:15和12:40关机。(5分钟后关机)

import os
from pynput import mouse, keyboard
import tkinter as tk
from tkinter import font, messagebox
import threading
import subprocess
import platform
from datetime import datetime, time
import time


# 开机运行提示
def show_custom_message_box():
    # 创建自定义的Tkinter窗口
    root = tk.Tk()
    root.withdraw()  # 隐藏主窗口

    # 创建顶级窗口作为信息框
    top = tk.Toplevel(root)
    top.overrideredirect(True)  # 移除窗口边框
    top.title("自动关机小程序")
    top.attributes('-fullscreen', False)  # 移除全屏模式
    top.attributes('-topmost', True)  # 窗口置顶
    top.overrideredirect(False)  # 在设置属性后再关闭overrideredirect

    # 设置窗口背景色为黑色
    top.configure(bg='black')

    # 设置字体
    font_size = 18  # 字体大小
    custom_font = font.Font(family='黑体', size=font_size, weight='bold')

    # 创建标签并设置分段文本、字体和背景色
    text = """    
你想公告的内容
    """

    label = tk.Label(top, text=text, font=custom_font, justify='left', bg='black',
                     fg='cyan')  # 设置前景色为白色
    label.pack(pady=500)  # pady添加垂直填充

    # 创建确定按钮,并设置背景色和前景色
    ok_button = tk.Button(top, text="确定", command=top.destroy, bg='black', fg='cyan')
    ok_button.pack(side=tk.BOTTOM, pady=10)  # pady添加底部填充

    label.pack(pady=50, padx=10, fill='x', expand=True)

    # 进入Tkinter的事件循环,等待用户交互
    top.mainloop()


# 在新线程中显示自定义消息框
threading.Thread(target=show_custom_message_box).start()

# 设置超时时间(秒)
timeout = 300  # 5分钟 300

# 设置剩余5min提醒
time_ten = 300  # 5分钟 300

# 用来定义剩余10分钟是否触发过
show_message_if = False

# 定义一个变量来跟踪是否有活动
is_active = False


# 定义一个函数,在鼠标或键盘事件触发时设置is_active为True
def on_event(event):
    global is_active
    is_active = True


def on_move(x, y):
    global is_active
    is_active = True


def on_click(x, y, button, pressed):
    global is_active
    is_active = True


def show_message():
    global show_message_if
    messagebox.showinfo("提示", "若无操作则5分钟后自动关机")


# 创建提示窗口
root = tk.Tk()
root.withdraw()  # 隐藏主窗口

now_if = datetime.now()
current_hour1 = now_if.hour
if current_hour1 >= 13:
    # 获取当前时间
    now = datetime.now()
    target_time = datetime.combine(now.date(),
                                   datetime.min.time().replace(hour=21, minute=35, second=0, microsecond=0))  # 21:35

    while True:  # 让这个一直循环直到时间到晚上9点35以后
        now_1 = datetime.now()
        if now_1 >= target_time:
            break
        else:
            time.sleep(1)

    # 使用pynput监听鼠标和键盘事件
    mouse_listener = mouse.Listener(on_move=on_move, on_click=on_click)
    keyboard_listener = keyboard.Listener(on_press=on_event)

    # 启动监听器
    mouse_listener.start()
    keyboard_listener.start()
    # 计时器
    start_time = time.time()

    while True:
        if time.time() - start_time > time_ten and show_message_if == False:
            threading.Thread(target=show_message).start()
            show_message_if = True

        if is_active:  # 如果有操作了,就重置时间
            # 重置计时器和状态
            start_time = time.time()
            is_active = False
            show_message_if = False

        elif time.time() - start_time > timeout:
            # 执行关机命令
            os.system("shutdown /s /t 1")  # Windows系统关机命令

            continue
        time.sleep(1)  # 每秒检查一次
else:
    now = datetime.now()
    target_time = datetime.combine(now.date(),
                                   datetime.min.time().replace(hour=12, minute=10, second=0, microsecond=0))  # 12:10

    while True:  # 让这个一直循环直到时间到中午12:10分点半以后
        now_1 = datetime.now()
        if now_1 >= target_time:
            break
        else:
            time.sleep(1)

    # 使用pynput监听鼠标和键盘事件
    mouse_listener = mouse.Listener(on_move=on_move, on_click=on_click)
    keyboard_listener = keyboard.Listener(on_press=on_event)

    # 启动监听器
    mouse_listener.start()
    keyboard_listener.start()
    # 计时器
    start_time = time.time()

    while True:
        if time.time() - start_time > time_ten and show_message_if == False:
            threading.Thread(target=show_message).start()
            show_message_if = True

        if is_active:
            # 重置计时器和状态
            start_time = time.time()
            is_active = False
            show_message_if = False

        elif time.time() - start_time > timeout:
            # 执行关机命令
            os.system("shutdown /s /t 1")  # Windows系统关机命令

            continue
        time.sleep(1)  # 每秒检查一次

# 停止监听器
mouse_listener.stop()
keyboard_listener.stop()

# 确保监听器不再运行
mouse_listener.join()
keyboard_listener.join()

  • 10
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值