基于Python開發(fā)電腦定時關(guān)機工具
1. 簡介
這個程序就像一個“忠實的管家”,幫你按時關(guān)掉電腦,而且全程不需要你多做什么。你只需要設(shè)定好時間,它就能在指定的時刻執(zhí)行關(guān)機任務(wù),絕對精準,絕對準時。如果你突然改變主意,管家也非常懂事,立刻取消任務(wù),并且讓你確認是否真的要放棄關(guān)機。
功能概述
1.選擇關(guān)機時間:
你可以選擇一個未來的時間點(絕對時間),或者從現(xiàn)在開始延遲一段時間(相對時間),就像預(yù)約鬧鐘一樣,精確到秒!
2.定時關(guān)機:
設(shè)置好關(guān)機時間后,程序會自動計算倒計時,不管你去做什么,它都會提醒你:“再過 XX 小時 XX 分鐘 XX 秒,電腦就會乖乖關(guān)機。”
3.隨時取消:
你改變了主意,突然不想關(guān)機了?沒問題!隨時點擊取消,它會立馬停止關(guān)機進程,不會讓你后悔。
4.倒計時提醒:
在你設(shè)置的時間到來之前,它會在界面上顯示倒計時,讓你時刻知道剩余的時間。想象一下,一邊工作一邊看著電腦準備入睡的樣子。
簡而言之,這個工具就像是一個非常懂事的“關(guān)機助手”,不會打擾你,卻能在你需要它的時候,安靜地完成任務(wù)。
2. 運行效果



3. 相關(guān)源碼
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 = '執(zhí)行'
BUTTON_CANCEL_TEXT = '取消'
BUTTON_EXECUTING_TEXT = '執(zhí)行中...'
LABEL_COUNTDOWN_DEFAULT = '未設(shè)置定時關(guān)機'
ALERT_FUTURE_TIME = '請選擇一個未來的時間!'
ALERT_CONFIRM_CANCEL = '是否要修改定時關(guān)機設(shè)置?'
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('定時關(guān)機工具')
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)
# 倒計時顯示區(qū)域
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)
# 時間設(shè)置區(qū)域
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):
"""設(shè)置時間選擇控件和按鈕"""
settings_widget = QWidget()
settings_layout = QHBoxLayout(settings_widget)
# 時間選擇區(qū)域
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)
# 按鈕區(qū)域
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):
"""執(zhí)行定時關(guān)機"""
shutdown_time = self.calculate_shutdown_time()
if not shutdown_time:
return
# 設(shè)置關(guān)機命令
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):
"""計算定時關(guān)機時間"""
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):
"""更新按鈕狀態(tài)"""
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):
"""取消定時關(guān)機"""
reply = QMessageBox.question(self, '確認', ALERT_CONFIRM_CANCEL,
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No)
if reply == QMessageBox.StandardButton.Yes:
# 取消當前關(guān)機命令
subprocess.run(['shutdown', '/a'])
self.reset_ui()
else:
subprocess.run(['shutdown', '/a'])
self.close()
def reset_ui(self):
"""重置UI狀態(tài)"""
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'距離關(guān)機還有 {hours:02d}小時 {minutes:02d}分 {seconds:02d}秒')
if __name__ == '__main__':
app = QApplication(sys.argv)
app.setStyle('Fusion') # 使用 Fusion 風(fēng)格,接近 Windows 10 風(fēng)格
window = ShutdownTimer()
window.show()
sys.exit(app.exec())
到此這篇關(guān)于基于Python開發(fā)電腦定時關(guān)機工具的文章就介紹到這了,更多相關(guān)Python電腦定時關(guān)機內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python不同目錄間進行模塊調(diào)用的實現(xiàn)方法
這篇文章主要介紹了Python不同目錄間進行模塊調(diào)用的實現(xiàn)方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-01-01
解決ToPILImage時出現(xiàn)維度報錯問題pic should be 2/3 d
這篇文章主要介紹了解決ToPILImage時出現(xiàn)維度報錯問題pic should be 2/3 dimensional. Got 4 dimensions.具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-02-02
python sorted()函數(shù)的key參數(shù)使用說明
文章介紹了Python中的sort()和sorted()方法的區(qū)別及其用法,sort()是list的方法,不能對所有可迭代對象進行排序,且在原地對列表排序,無返回值,sorted()是內(nèi)置函數(shù),可以對所有可迭代對象進行排序,并返回一個新的排序后的列表,文章還提供了sorted()的用法示例2025-11-11
CentOS 6.5中安裝Python 3.6.2的方法步驟
centos 6.5默認自帶的python版本為2.6,而下面這篇文章主要給大家介紹了關(guān)于在CentOS 6.5中安裝Python 3.6.2的方法步驟,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2017-12-12
通過python爬蟲mechanize庫爬取本機ip地址的方法
python中的mechanize算是一個比較古老的庫了,在python2的時代中,使用的多一些,在python3以后就很少使用了,現(xiàn)在已經(jīng)是2202年了,可能很多人都沒聽說過mechanize,這不要緊,我們先來簡單的講解一下,如何使用mechanize,感興趣的朋友一起看看吧2022-08-08
python+pyqt實現(xiàn)12306圖片驗證效果
這篇文章主要為大家詳細介紹了python+pyqt實現(xiàn)12306圖片驗證效果,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-10-10

