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())
相关推荐
我先去打把游戏先几秒前
ESP32开发指南(基于IDF):连接AWS,乐鑫官方esp-aws-iot-master例程实验、跑通
开发语言·笔记·单片机·物联网·学习·云计算·aws
极客数模20 分钟前
2025年(第六届)“大湾区杯”粤港澳金融数学建模竞赛准备!严格遵循要求,拿下大奖!
大数据·python·数学建模·金融·分类·图论·boosting
逻极32 分钟前
Rust数据类型(上):标量类型全解析
开发语言·后端·rust
倔强青铜三34 分钟前
苦练Python第73天:玩转对象持久化,pickle模块极速入门
人工智能·python·面试
Zhangzy@35 分钟前
Rust 编译优化选项
android·开发语言·rust
百锦再39 分钟前
第2章 第一个Rust程序
java·开发语言·后端·rust·eclipse·tomcat·hibernate
Zhangzy@40 分钟前
Rust 中的注释与文档注释实践指南
开发语言·后端·rust
像风一样自由202041 分钟前
使用 Rust 开发图片切分工具:从零到发布的完整指南
开发语言·后端·rust
程序员三藏1 小时前
Postman持久化保存/设置断言详解
自动化测试·软件测试·python·测试工具·职场和发展·接口测试·postman
java1234_小锋1 小时前
PyTorch2 Python深度学习 - 卷积神经网络(CNN)介绍实例 - 使用MNIST识别手写数字示例
python·深度学习·cnn·pytorch2