使用Python打造高顏值系統(tǒng)時間控制器
一、概述:當時間管理遇上現(xiàn)代UI
在日常開發(fā)中,我們經(jīng)常需要精確控制系統(tǒng)時間,但Windows自帶的時間設(shè)置工具實在太簡陋了!今天我要分享的是用PyQt5開發(fā)的高顏值時間控制器,它不僅顏值在線,還具備:
- 現(xiàn)代化Fluent Design界面
- 實時時間顯示(精確到秒)
- 可視化時間修改(帶日歷控件)
- NTP網(wǎng)絡(luò)時間同步模擬
- 智能權(quán)限檢測(自動識別管理員權(quán)限)
技術(shù)亮點:本項目的界面設(shè)計參考了Windows 11的Fluent UI設(shè)計規(guī)范,采用QSS實現(xiàn)深度樣式定制,是學(xué)習PyQt5現(xiàn)代化開發(fā)的絕佳案例!

二、功能全景:六大核心模塊解析
2.1 實時時鐘模塊
class ModernTerminalLabel(QLabel):
"""?? 動態(tài)時鐘標簽"""
def __init__(self):
self.setStyleSheet("""
background: qlineargradient(x1:0, y1:0, x2:1, y2:1,
stop:0 #3498db, stop:1 #2c3e50);
border-radius: 10px;
color: white;
padding: 15px;
""")
自定義漸變效果時鐘標簽
2.2 時間設(shè)置模塊
功能特點:
- 集成QDateTimeEdit控件
- 帶彈出式日歷選擇
- 自動檢測管理員權(quán)限
2.3 NTP同步模塊
支持服務(wù)器列表:
pool.ntp.org(默認)time.google.com(谷歌)time.windows.com(微軟)ntp.aliyun.com(阿里云)
三、效果展示:眼見為實
3.1 主界面(Light模式)

3.2 幫助頁面展示

3.3 時間同步演示

四、手把手實現(xiàn)教程
4.1 環(huán)境準備
pip install PyQt5==5.15.9 pywin32
4.2 核心類結(jié)構(gòu)

4.3 關(guān)鍵代碼解析
時間修改功能
def change_datetime(self):
try:
# ??? 權(quán)限檢查
if not ctypes.windll.shell32.IsUserAnAdmin():
self.show_error("?? 需要管理員權(quán)限!")
return
# ?? 設(shè)置系統(tǒng)時間
ctypes.windll.kernel32.SetLocalTime(byref(time_struct))
self.show_success("? 時間修改成功!")
except Exception as e:
self.show_error(f"? 錯誤:{str(e)}")
NTP同步動畫
def update_sync_status(self, step):
steps = [
"??? 正在連接服務(wù)器...",
"? 獲取時間數(shù)據(jù)...",
"?? 校準系統(tǒng)中...",
"?? 同步完成!"
]
self.status_label.setText(steps[step])
五、源碼獲取與進階改造
5.1 完整項目下載
import sys
import ctypes
import platform
from datetime import datetime
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout,
QHBoxLayout, QLabel, QDateTimeEdit, QPushButton,
QMessageBox, QTabWidget, QLineEdit, QComboBox,
QFormLayout, QFrame, QSizePolicy, QSpacerItem)
from PyQt5.QtCore import QDateTime, Qt, QTimer
from PyQt5.QtGui import QFont, QColor, QPalette, QFontDatabase, QIcon
class ModernTerminalLabel(QLabel):
"""現(xiàn)代化終端風格標簽"""
def __init__(self, text, font_size=14, bold=False):
super().__init__(text)
self.setAlignment(Qt.AlignCenter)
self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
# 字體選擇優(yōu)先級列表
preferred_fonts = ["Segoe UI", "Arial", "Helvetica", "Microsoft YaHei", "PingFang SC"]
font_db = QFontDatabase()
available_fonts = font_db.families()
# 選擇第一個可用的字體
selected_font = "Arial" # 默認回退字體
for font_name in preferred_fonts:
if font_name in available_fonts:
selected_font = font_name
break
font = QFont(selected_font, font_size)
font.setBold(bold)
self.setFont(font)
self.setStyleSheet("color: #2c3e50;")
class ModernButton(QPushButton):
"""現(xiàn)代化按鈕"""
def __init__(self, text, icon=None, parent=None):
super().__init__(text, parent)
self.setCursor(Qt.PointingHandCursor)
self.setMinimumHeight(42)
if icon:
self.setIcon(QIcon.fromTheme(icon))
self.setStyleSheet("""
QPushButton {
background-color: #3498db;
color: white;
border: none;
border-radius: 6px;
padding: 10px 20px;
font-family: 'Segoe UI';
font-size: 14px;
font-weight: medium;
min-width: 140px;
}
QPushButton:hover {
background-color: #2980b9;
}
QPushButton:pressed {
background-color: #1a6ca8;
}
QPushButton:disabled {
background-color: #bdc3c7;
}
""")
class TimeController(QMainWindow):
def __init__(self):
super().__init__()
# 窗口設(shè)置
self.setWindowTitle("?? 高級時間控制器")
self.setWindowIcon(QIcon.fromTheme("clock"))
self.resize(608, 650)
self.setMinimumSize(608, 650)
# 設(shè)置現(xiàn)代化主題
self.setAutoFillBackground(True)
palette = self.palette()
palette.setColor(QPalette.Window, QColor(240, 242, 245))
palette.setColor(QPalette.Base, QColor(255, 255, 255))
palette.setColor(QPalette.Text, QColor(44, 62, 80))
self.setPalette(palette)
# 主部件
central_widget = QWidget()
self.setCentralWidget(central_widget)
# 主布局
main_layout = QVBoxLayout(central_widget)
main_layout.setContentsMargins(30, 30, 30, 20)
main_layout.setSpacing(25)
# 初始化UI
self.init_ui(main_layout)
# 狀態(tài)欄
self.statusBar().setStyleSheet("""
QStatusBar {
background-color: #ecf0f1;
color: #7f8c8d;
border-top: 1px solid #d5dbdb;
font-family: 'Segoe UI';
font-size: 11px;
height: 24px;
}
""")
self.statusBar().showMessage("?? 系統(tǒng)準備就緒 | 當前用戶: {}".format(platform.node()))
# 設(shè)置定時器每秒更新一次時間
self.timer = QTimer(self)
self.timer.timeout.connect(self.update_current_time)
self.timer.start(1000) # 1000毫秒 = 1秒
def init_ui(self, layout):
"""初始化用戶界面"""
# 當前時間顯示
self.time_display = QWidget()
time_display_layout = QVBoxLayout(self.time_display)
time_display_layout.setContentsMargins(0, 0, 0, 0)
time_label = ModernTerminalLabel("當前系統(tǒng)時間", 14)
time_label.setAlignment(Qt.AlignLeft)
time_label.setStyleSheet("color: #7f8c8d; margin-bottom: 5px;")
time_display_layout.addWidget(time_label)
self.time_value = ModernTerminalLabel("", 20)
self.time_value.setStyleSheet("""
QLabel {
background-color: white;
color: #2c3e50;
border: 1px solid #d5dbdb;
border-radius: 8px;
padding: 15px;
margin: 5px 0;
}
""")
time_display_layout.addWidget(self.time_value)
layout.addWidget(self.time_display)
self.update_current_time()
# 標簽頁區(qū)域
self.tabs = QTabWidget()
self.tabs.setStyleSheet("""
QTabWidget::pane {
border: 1px solid #d5dbdb;
border-radius: 8px;
background: white;
margin-top: 10px;
}
QTabBar::tab {
background: #ecf0f1;
color: #7f8c8d;
border: 1px solid #d5dbdb;
border-bottom: none;
border-top-left-radius: 8px;
border-top-right-radius: 8px;
padding: 10px 20px;
margin-right: 4px;
font-family: 'Segoe UI';
font-size: 13px;
}
QTabBar::tab:selected {
background: white;
color: #2c3e50;
border-bottom: 2px solid #3498db;
}
QTabBar::tab:hover {
background: #e0e6e9;
}
""")
# 創(chuàng)建標簽頁
self.create_manual_tab()
self.create_sync_tab()
layout.addWidget(self.tabs)
# 底部按鈕區(qū)域
button_layout = QHBoxLayout()
button_layout.setSpacing(15)
# 添加彈性空間使按鈕右對齊
button_layout.addStretch()
refresh_btn = ModernButton("?? 刷新時間", "view-refresh")
refresh_btn.clicked.connect(self.update_current_time)
button_layout.addWidget(refresh_btn)
help_btn = ModernButton("?? 幫助", "help-contents")
help_btn.clicked.connect(self.show_help)
button_layout.addWidget(help_btn)
exit_btn = ModernButton("?? 退出", "application-exit")
exit_btn.clicked.connect(self.close)
button_layout.addWidget(exit_btn)
layout.addLayout(button_layout)
def create_manual_tab(self):
"""創(chuàng)建手動設(shè)置時間標簽頁"""
tab = QWidget()
layout = QVBoxLayout(tab)
layout.setContentsMargins(20, 20, 20, 20)
layout.setSpacing(25)
# 說明文字
info_label = ModernTerminalLabel("??? 手動調(diào)整系統(tǒng)日期和時間", 16)
info_label.setStyleSheet("color: #2c3e50; margin-bottom: 15px;")
layout.addWidget(info_label)
# 表單區(qū)域
form_layout = QFormLayout()
form_layout.setHorizontalSpacing(20)
form_layout.setVerticalSpacing(15)
form_layout.setLabelAlignment(Qt.AlignRight)
# 日期時間選擇器
self.datetime_edit = QDateTimeEdit()
self.datetime_edit.setDisplayFormat("yyyy-MM-dd HH:mm:ss")
self.datetime_edit.setDateTime(QDateTime.currentDateTime())
self.datetime_edit.setCalendarPopup(True)
self.datetime_edit.setStyleSheet("""
QDateTimeEdit {
background-color: white;
color: #2c3e50;
border: 1px solid #d5dbdb;
border-radius: 6px;
padding: 10px;
font-family: 'Segoe UI';
font-size: 14px;
min-width: 220px;
}
QDateTimeEdit:hover {
border: 1px solid #bdc3c7;
}
QCalendarWidget {
background-color: white;
color: #2c3e50;
font-family: 'Segoe UI';
}
""")
dt_label = QLabel("設(shè)置日期時間:")
dt_label.setStyleSheet("color: #7f8c8d; font-family: 'Segoe UI'; font-size: 14px;")
form_layout.addRow(dt_label, self.datetime_edit)
layout.addLayout(form_layout)
# 應(yīng)用按鈕
apply_btn = ModernButton("?? 應(yīng)用時間設(shè)置", "document-save")
apply_btn.clicked.connect(self.change_datetime)
layout.addWidget(apply_btn, 0, Qt.AlignRight)
self.tabs.addTab(tab, "?? 手動設(shè)置")
def create_sync_tab(self):
"""創(chuàng)建時間同步標簽頁"""
tab = QWidget()
layout = QVBoxLayout(tab)
layout.setContentsMargins(20, 20, 20, 20)
layout.setSpacing(25)
# 說明文字
info_label = ModernTerminalLabel("?? 通過網(wǎng)絡(luò)時間協(xié)議(NTP)同步", 16)
info_label.setStyleSheet("color: #2c3e50; margin-bottom: 15px;")
layout.addWidget(info_label)
# 表單區(qū)域
form_layout = QFormLayout()
form_layout.setHorizontalSpacing(20)
form_layout.setVerticalSpacing(15)
form_layout.setLabelAlignment(Qt.AlignRight)
# 服務(wù)器選擇
server_label = QLabel("時間服務(wù)器:")
server_label.setStyleSheet("color: #7f8c8d; font-family: 'Segoe UI'; font-size: 14px;")
self.server_combo = QComboBox()
self.server_combo.addItems([
"pool.ntp.org (默認)",
"time.google.com (Google)",
"time.windows.com (Microsoft)",
"time.apple.com (Apple)",
"ntp.aliyun.com (阿里云)",
"ntp1.tencent.com (騰訊云)"
])
self.server_combo.setEditable(True)
self.server_combo.setStyleSheet("""
QComboBox {
background-color: white;
color: #2c3e50;
border: 1px solid #d5dbdb;
border-radius: 6px;
padding: 8px;
font-family: 'Segoe UI';
font-size: 14px;
min-width: 250px;
}
QComboBox:hover {
border: 1px solid #bdc3c7;
}
QComboBox QAbstractItemView {
background-color: white;
selection-background-color: #3498db;
selection-color: white;
font-family: 'Segoe UI';
font-size: 13px;
}
""")
form_layout.addRow(server_label, self.server_combo)
layout.addLayout(form_layout)
# 同步按鈕
sync_btn = ModernButton("?? 立即同步", "network-workgroup")
sync_btn.clicked.connect(self.start_ntp_sync)
layout.addWidget(sync_btn, 0, Qt.AlignRight)
# 同步狀態(tài)區(qū)域
sync_status_layout = QVBoxLayout()
sync_status_layout.setSpacing(5)
status_label = QLabel("同步狀態(tài):")
status_label.setStyleSheet("color: #7f8c8d; font-family: 'Segoe UI'; font-size: 14px;")
sync_status_layout.addWidget(status_label)
self.sync_status = QLabel("尚未同步")
self.sync_status.setStyleSheet("""
QLabel {
background-color: white;
color: #7f8c8d;
border: 1px solid #d5dbdb;
border-radius: 8px;
padding: 12px;
font-family: 'Segoe UI';
font-size: 13px;
}
""")
sync_status_layout.addWidget(self.sync_status)
layout.addLayout(sync_status_layout)
self.tabs.addTab(tab, "?? 網(wǎng)絡(luò)同步")
def update_current_time(self):
"""更新當前時間顯示"""
now = datetime.now()
self.time_value.setText(f"?? {now.strftime('%Y年%m月%d日 %H:%M:%S')}")
# 只在手動刷新時更新狀態(tài)欄消息
if not hasattr(self, 'is_timer_update'):
self.statusBar().showMessage(f"? 時間已刷新 | {now.strftime('%A %Y-%m-%d %H:%M:%S')}", 3000)
# 設(shè)置標志位表示這是定時器觸發(fā)的更新
self.is_timer_update = True
QTimer.singleShot(100, lambda: delattr(self, 'is_timer_update'))
def change_datetime(self):
"""更改系統(tǒng)日期時間"""
if platform.system() != "Windows":
self.show_message("? 錯誤", "?? 僅支持Windows系統(tǒng)", QMessageBox.Critical)
return
if not ctypes.windll.shell32.IsUserAnAdmin():
self.show_message("? 權(quán)限不足", "?? 需要管理員權(quán)限才能修改系統(tǒng)時間", QMessageBox.Critical)
return
new_datetime = self.datetime_edit.dateTime().toPyDateTime()
try:
ctypes.windll.kernel32.SetLocalTime(ctypes.byref(self.get_system_time_struct(new_datetime)))
self.update_current_time()
self.show_message("? 成功", "?? 系統(tǒng)時間已成功修改", QMessageBox.Information)
except Exception as e:
self.show_message("? 錯誤", f"?? 修改失敗: {str(e)}", QMessageBox.Critical)
def start_ntp_sync(self):
"""開始NTP時間同步"""
server = self.server_combo.currentText().split(" ")[0] # 獲取服務(wù)器地址部分
if not server:
self.show_message("?? 警告", "?? 請選擇或輸入有效的時間服務(wù)器地址", QMessageBox.Warning)
return
# 模擬同步過程
self.sync_status.setText("? 正在連接服務(wù)器 {}...".format(server))
QTimer.singleShot(1500, lambda: self.update_sync_status(1, server))
def update_sync_status(self, step, server):
"""更新同步狀態(tài)"""
if step == 1:
self.sync_status.setText("?? 正在從 {} 獲取時間數(shù)據(jù)...".format(server))
QTimer.singleShot(1500, lambda: self.update_sync_status(2, server))
elif step == 2:
self.sync_status.setText("?? 正在校準系統(tǒng)時間...")
QTimer.singleShot(1500, lambda: self.finish_ntp_sync(server))
def finish_ntp_sync(self, server):
"""完成NTP同步"""
now = datetime.now()
self.sync_status.setText("? 同步成功\n服務(wù)器: {}\n時間: {}".format(
server, now.strftime("%Y-%m-%d %H:%M:%S")))
self.datetime_edit.setDateTime(QDateTime.currentDateTime())
self.update_current_time()
self.show_message("? 成功", "?? 已成功從 {} 同步時間".format(server), QMessageBox.Information)
def show_help(self):
"""顯示幫助信息"""
help_text = """
<h3>?? 時間控制器幫助</h3>
<h4>?? 手動設(shè)置時間</h4>
<p>1. 在日期時間選擇器中選擇新的日期和時間</p>
<p>2. 點擊"應(yīng)用時間設(shè)置"按鈕</p>
<p>3. 需要管理員權(quán)限才能修改系統(tǒng)時間</p>
<h4>?? 網(wǎng)絡(luò)時間同步</h4>
<p>1. 從下拉列表選擇時間服務(wù)器</p>
<p>2. 或手動輸入自定義NTP服務(wù)器地址</p>
<p>3. 點擊"立即同步"按鈕</p>
<h4>?? 注意事項</h4>
<p>? 僅支持Windows系統(tǒng)</p>
<p>? 修改系統(tǒng)時間需要管理員權(quán)限</p>
<p>? 網(wǎng)絡(luò)同步需要有效的互聯(lián)網(wǎng)連接</p>
<p>? 建議使用可靠的時間服務(wù)器</p>
"""
msg = QMessageBox(self)
msg.setWindowTitle("? 幫助")
msg.setTextFormat(Qt.RichText)
msg.setText(help_text)
msg.setIcon(QMessageBox.Information)
msg.setStyleSheet("""
QMessageBox {
background-color: white;
font-family: 'Segoe UI';
}
QLabel {
color: #2c3e50;
font-size: 13px;
}
QPushButton {
background-color: #3498db;
color: white;
border: none;
border-radius: 6px;
padding: 8px 16px;
min-width: 80px;
font-family: 'Segoe UI';
}
QPushButton:hover {
background-color: #2980b9;
}
""")
msg.exec_()
def get_system_time_struct(self, dt):
"""將datetime對象轉(zhuǎn)換為SYSTEMTIME結(jié)構(gòu)體"""
class SYSTEMTIME(ctypes.Structure):
_fields_ = [
('wYear', ctypes.c_uint16),
('wMonth', ctypes.c_uint16),
('wDayOfWeek', ctypes.c_uint16),
('wDay', ctypes.c_uint16),
('wHour', ctypes.c_uint16),
('wMinute', ctypes.c_uint16),
('wSecond', ctypes.c_uint16),
('wMilliseconds', ctypes.c_uint16)
]
st = SYSTEMTIME()
st.wYear = dt.year
st.wMonth = dt.month
st.wDay = dt.day
st.wHour = dt.hour
st.wMinute = dt.minute
st.wSecond = dt.second
st.wMilliseconds = dt.microsecond // 1000
return st
def show_message(self, title, text, icon):
"""顯示現(xiàn)代化消息框"""
msg = QMessageBox(self)
msg.setWindowTitle(title)
msg.setText(text)
msg.setIcon(icon)
msg.setStyleSheet("""
QMessageBox {
background-color: white;
font-family: 'Segoe UI';
}
QLabel {
color: #2c3e50;
font-size: 14px;
}
QPushButton {
background-color: #3498db;
color: white;
border: none;
border-radius: 6px;
padding: 8px 16px;
min-width: 80px;
font-family: 'Segoe UI';
}
QPushButton:hover {
background-color: #2980b9;
}
""")
msg.exec_()
if __name__ == "__main__":
app = QApplication(sys.argv)
app.setStyle("Fusion")
# 設(shè)置應(yīng)用程序字體
font_db = QFontDatabase()
preferred_fonts = ["Segoe UI", "Arial", "Helvetica", "Microsoft YaHei", "PingFang SC"]
selected_font = "Arial"
for font_name in preferred_fonts:
if font_name in font_db.families():
selected_font = font_name
break
font = QFont(selected_font, 10)
app.setFont(font)
window = TimeController()
window.show()
sys.exit(app.exec_())
5.2 二次開發(fā)建議
添加真實NTP協(xié)議支持:
import ntplib
def real_ntp_sync(server):
client = ntplib.NTPClient()
response = client.request(server)
return response.tx_time
實現(xiàn)多主題切換:
def set_theme(theme):
if theme == "dark":
apply_dark_theme()
else:
apply_light_theme()
六、總結(jié)與展望
6.1 項目總結(jié)
通過本項目我們掌握了:
- PyQt5現(xiàn)代化界面開發(fā)技巧
- Windows系統(tǒng)時間管理API
- QSS樣式表深度定制
- 狀態(tài)機動畫實現(xiàn)
6.2 未來升級計劃
- 增加Linux/macOS支持
- 添加定時同步功能
- 實現(xiàn)時間修改歷史記錄
- 開發(fā)插件系統(tǒng)
以上就是使用Python打造高顏值系統(tǒng)時間控制器的詳細內(nèi)容,更多關(guān)于Python系統(tǒng)時間控制器的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python多叉樹的構(gòu)造及取出節(jié)點數(shù)據(jù)(treelib)的方法
今天小編就為大家分享一篇Python多叉樹的構(gòu)造及取出節(jié)點數(shù)據(jù)(treelib)的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-08-08
python三種數(shù)據(jù)結(jié)構(gòu)及13種創(chuàng)建方法總結(jié)
拿Python來說,數(shù)據(jù)結(jié)構(gòu)的概念也是超級重要,不同的數(shù)據(jù)結(jié)構(gòu),有著不同的函數(shù),供我們調(diào)用,接下來,我們分別來介紹字符串、列表、字典的創(chuàng)建方法2021-09-09
利用Python將每日一句定時推送至微信的實現(xiàn)方法
這篇文章主要給大家介紹了關(guān)于利用Python將每日一句定時推送至微信的實現(xiàn)方法,文中通過示例代碼將實現(xiàn)的步驟一步步介紹的非常詳細,需要的朋友可以參考借鑒,下面隨著小編來一起學(xué)習學(xué)習吧2018-08-08
pytorch實現(xiàn)用Resnet提取特征并保存為txt文件的方法
今天小編大家分享一篇pytorch實現(xiàn)用Resnet提取特征并保存為txt文件的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-08-08
python實現(xiàn)批量監(jiān)控網(wǎng)站
本文給大家分享的是一個非常實用的,python實現(xiàn)多網(wǎng)站的可用性監(jiān)控的腳本,并附上核心點解釋,有相同需求的小伙伴可以參考下2016-09-09
Python實現(xiàn)多種場景下查找并高亮Word文檔中的文本
在處理長篇 Word 文檔時,快速定位關(guān)鍵信息并將其突出顯示是一項非常實用的技能,本文將深入探討如何使用 Python 實現(xiàn)多種場景下的 Word 文檔文本查找與高亮功能,有需要的小伙伴可以了解下2026-03-03

