Python 电脑定时关机工具

Python 电脑定时关机工具

相关资源文件已经打包成EXE文件,可双击直接运行程序,且文章末尾已附上相关源码,以供大家学习交流,博主主页还有更多Python相关程序案例,秉着开源精神的想法,望大家喜欢,点个关注不迷路!!!

1. 简介:

这个程序就像一个"忠实的管家",帮你按时关掉电脑,而且全程不需要你多做什么。你只需要设定好时间,它就能在指定的时刻执行关机任务,绝对精准,绝对准时。如果你突然改变主意,管家也非常懂事,立刻取消任务,并且让你确认是否真的要放弃关机。

功能概述:

选择关机时间:

你可以选择一个未来的时间点(绝对时间),或者从现在开始延迟一段时间(相对时间),就像预约闹钟一样,精确到秒!
定时关机:

设置好关机时间后,程序会自动计算倒计时,不管你去做什么,它都会提醒你:"再过 XX 小时 XX 分钟 XX 秒,电脑就会乖乖关机。"

随时取消:

你改变了主意,突然不想关机了?没问题!随时点击取消,它会立马停止关机进程,不会让你后悔。

倒计时提醒:

在你设置的时间到来之前,它会在界面上显示倒计时,让你时刻知道剩余的时间。想象一下,一边工作一边看着电脑准备入睡的样子。

简而言之,这个工具就像是一个非常懂事的"关机助手",不会打扰你,却能在你需要它的时候,安静地完成任务。

2. 运行效果:



3. 相关源码:

python 复制代码
import sys
import datetime
import subprocess
from PyQt6.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, 
                             QHBoxLayout, QLabel, QPushButton, QRadioButton, 
                             QDateTimeEdit, QTimeEdit, QMessageBox, QGroupBox, 
                             QSpacerItem, QSizePolicy)
from PyQt6.QtCore import Qt, QTimer, QDateTime
from PyQt6.QtGui import QFont, QColor

# 常量定义
BUTTON_EXECUTE_TEXT = '执行'
BUTTON_CANCEL_TEXT = '取消'
BUTTON_EXECUTING_TEXT = '执行中...'
LABEL_COUNTDOWN_DEFAULT = '未设置定时关机'
ALERT_FUTURE_TIME = '请选择一个未来的时间!'
ALERT_CONFIRM_CANCEL = '是否要修改定时关机设置?'


class ShutdownTimer(QMainWindow):
    def __init__(self):
        super().__init__()
        self.shutdown_time = None
        self.timer = QTimer()
        self.timer.timeout.connect(self.update_countdown)
        self.init_ui()

    def init_ui(self):
        """初始化界面元素"""
        self.setWindowTitle('定时关机工具')
        screen = QApplication.primaryScreen().geometry()
        self.setGeometry(screen.width() // 4, screen.height() // 4, 585, 253)  # 修改窗口尺寸为583x614

        # 主布局
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        layout = QVBoxLayout(central_widget)

        # 倒计时显示区域
        self.countdown_label = QLabel(LABEL_COUNTDOWN_DEFAULT)
        self.countdown_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.countdown_label.setStyleSheet("""
            QLabel {
                background-color: black;
                color: red;
                padding: 20px;
                border: 2px solid gray;
                border-radius: 10px;
                font-size: 30px;
            }
        """)
        layout.addWidget(self.countdown_label)

        # 时间设置区域
        self.setup_time_settings(layout)

        # 信号连接
        self.absolute_radio.toggled.connect(self.toggle_time_input)
        self.execute_btn.clicked.connect(self.execute_shutdown)
        self.cancel_btn.clicked.connect(self.cancel_shutdown)

    def setup_time_settings(self, layout):
        """设置时间选择控件和按钮"""
        settings_widget = QWidget()
        settings_layout = QHBoxLayout(settings_widget)

        # 时间选择区域
        time_widget = QWidget()
        time_layout = QVBoxLayout(time_widget)

        # 单选按钮
        self.absolute_radio = QRadioButton('绝对时间')
        self.relative_radio = QRadioButton('相对时间')
        self.absolute_radio.setChecked(True)
        time_layout.addWidget(self.absolute_radio)
        time_layout.addWidget(self.relative_radio)

        # 时间选择器
        self.datetime_edit = QDateTimeEdit()
        self.datetime_edit.setDateTime(QDateTime.currentDateTime().addSecs(3600))  # 默认一小时后
        self.time_edit = QTimeEdit()
        self.time_edit.setTime(self.time_edit.time().addSecs(3600))  # 默认一个小时后

        time_layout.addWidget(self.datetime_edit)
        time_layout.addWidget(self.time_edit)
        self.time_edit.hide()  # 默认隐藏相对时间

        settings_layout.addWidget(time_widget)

        # 按钮区域
        button_widget = QWidget()
        button_layout = QVBoxLayout(button_widget)

        self.execute_btn = QPushButton(BUTTON_EXECUTE_TEXT)
        self.cancel_btn = QPushButton(BUTTON_CANCEL_TEXT)

        button_layout.addWidget(self.execute_btn)
        button_layout.addWidget(self.cancel_btn)

        settings_layout.addWidget(button_widget)
        layout.addWidget(settings_widget)

        # 添加空白间距
        spacer = QSpacerItem(20, 20, QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
        layout.addItem(spacer)

    def toggle_time_input(self):
        """切换时间输入方式"""
        if self.absolute_radio.isChecked():
            self.datetime_edit.show()
            self.time_edit.hide()
        else:
            self.datetime_edit.hide()
            self.time_edit.show()

    def execute_shutdown(self):
        """执行定时关机"""
        shutdown_time = self.calculate_shutdown_time()
        if not shutdown_time:
            return

        # 设置关机命令
        seconds = int((shutdown_time - datetime.datetime.now()).total_seconds())
        subprocess.run(['shutdown', '/s', '/t', str(seconds)])

        # 更新UI
        self.update_button_state(is_executing=True)

        # 启动倒计时
        self.shutdown_time = shutdown_time
        self.timer.start(1000)

    def calculate_shutdown_time(self):
        """计算定时关机时间"""
        if self.absolute_radio.isChecked():
            shutdown_time = self.datetime_edit.dateTime().toPyDateTime()
            if shutdown_time <= datetime.datetime.now():
                self.show_warning(ALERT_FUTURE_TIME)
                return None
        else:
            current_time = datetime.datetime.now()
            time_delta = datetime.timedelta(
                hours=self.time_edit.time().hour(),
                minutes=self.time_edit.time().minute(),
                seconds=self.time_edit.time().second()
            )
            shutdown_time = current_time + time_delta

        return shutdown_time

    def show_warning(self, message):
        """显示警告信息"""
        QMessageBox.warning(self, '警告', message)

    def update_button_state(self, is_executing):
        """更新按钮状态"""
        if is_executing:
            self.execute_btn.setEnabled(False)
            self.execute_btn.setText(BUTTON_EXECUTING_TEXT)
            self.execute_btn.setStyleSheet('background-color: #90EE90; color: gray;')
        else:
            self.execute_btn.setEnabled(True)
            self.execute_btn.setText(BUTTON_EXECUTE_TEXT)
            self.execute_btn.setStyleSheet('')

    def cancel_shutdown(self):
        """取消定时关机"""
        reply = QMessageBox.question(self, '确认', ALERT_CONFIRM_CANCEL,
                                     QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No)

        if reply == QMessageBox.StandardButton.Yes:
            # 取消当前关机命令
            subprocess.run(['shutdown', '/a'])
            self.reset_ui()
        else:
            subprocess.run(['shutdown', '/a'])
            self.close()

    def reset_ui(self):
        """重置UI状态"""
        self.shutdown_time = None
        self.timer.stop()
        self.countdown_label.setText(LABEL_COUNTDOWN_DEFAULT)
        self.update_button_state(is_executing=False)

    def update_countdown(self):
        """更新倒计时"""
        if self.shutdown_time:
            remaining = self.shutdown_time - datetime.datetime.now()
            if remaining.total_seconds() <= 0:
                self.timer.stop()
                return

            hours = remaining.seconds // 3600
            minutes = (remaining.seconds % 3600) // 60
            seconds = remaining.seconds % 60

            self.countdown_label.setText(
                f'距离关机还有 {hours:02d}小时 {minutes:02d}分 {seconds:02d}秒')


if __name__ == '__main__':
    app = QApplication(sys.argv)
    app.setStyle('Fusion')  # 使用 Fusion 风格,接近 Windows 10 风格
    window = ShutdownTimer()
    window.show()
    sys.exit(app.exec())
相关推荐
程序员爱钓鱼4 分钟前
用 Python 批量生成炫酷扫光 GIF 动效
后端·python·trae
封奚泽优7 分钟前
下降算法(Python实现)
开发语言·python·算法
java1234_小锋12 分钟前
基于Python深度学习的车辆车牌识别系统(PyTorch2卷积神经网络CNN+OpenCV4实现)视频教程 - 自定义字符图片数据集
python·深度学习·cnn·车牌识别
爱笑的眼睛1119 分钟前
深入理解MongoDB PyMongo API:从基础到高级实战
java·人工智能·python·ai
辣椒酱.25 分钟前
jupyter相关
python·jupyter
笃行客从不躺平29 分钟前
遇到大SQL怎么处理
java·开发语言·数据库·sql
郝学胜-神的一滴29 分钟前
Python中常见的内置类型
开发语言·python·程序人生·个人开发
g***B7381 小时前
Kotlin协程在Android中的使用
android·开发语言·kotlin
火白学安全1 小时前
《Python红队攻防零基础脚本编写:进阶篇(一)》
开发语言·python·安全·web安全·网络安全·系统安全
爱码小白1 小时前
PyQt5 QTimer总结
开发语言·qt