Python實(shí)現(xiàn)計(jì)算機(jī)時(shí)長(zhǎng)管理程序
1. 簡(jiǎn)介
這是一個(gè)包含倒計(jì)時(shí)、密碼驗(yàn)證、音頻控制、系統(tǒng)進(jìn)程監(jiān)控與終止等功能的程序。它通過(guò) tkinter 庫(kù)實(shí)現(xiàn)圖形用戶界面,利用其他模塊(如 pycaw 和 psutil)進(jìn)行系統(tǒng)操作。該程序旨在幫助用戶管理計(jì)算機(jī)使用時(shí)長(zhǎng),提供倒計(jì)時(shí)休息、密碼保護(hù)解除限制、監(jiān)控特定進(jìn)程并通過(guò)音頻靜音管理等功能。
功能:
1.倒計(jì)時(shí)管理:
用戶可以設(shè)置倒計(jì)時(shí)(小時(shí)、分鐘、秒),并通過(guò)窗口實(shí)時(shí)顯示剩余時(shí)間。
倒計(jì)時(shí)結(jié)束后,程序自動(dòng)進(jìn)行進(jìn)一步操作,如密碼驗(yàn)證或關(guān)機(jī)。
2.密碼驗(yàn)證:
用戶可通過(guò)輸入密碼來(lái)解除倒計(jì)時(shí)限制,若輸入正確,程序?qū)⑷∠o音并關(guān)閉驗(yàn)證窗口。
錯(cuò)誤輸入密碼多次后,程序會(huì)執(zhí)行關(guān)機(jī)操作。
3.音頻控制:
通過(guò) pycaw 庫(kù),程序可控制系統(tǒng)音頻設(shè)備的靜音與取消靜音。
4.進(jìn)程監(jiān)控與終止:
程序在后臺(tái)監(jiān)控特定進(jìn)程(如 Taskmgr.exe、perfmon.exe),如果這些進(jìn)程被檢測(cè)到,程序會(huì)自動(dòng)終止它們。
5.配置文件管理:
所有關(guān)鍵配置(如初始時(shí)間、剩余時(shí)間、日期、密碼)都存儲(chǔ)在 config.txt 文件中,程序在運(yùn)行時(shí)讀取和更新該文件,確保數(shù)據(jù)持續(xù)性。
6.系統(tǒng)關(guān)機(jī):
如果倒計(jì)時(shí)結(jié)束,或者用戶輸入密碼錯(cuò)誤超過(guò)設(shè)定次數(shù),程序會(huì)觸發(fā)系統(tǒng)關(guān)機(jī)操作。
注:
- config.txt文件不會(huì)自動(dòng)創(chuàng)建,沒(méi)有此文件程序會(huì)無(wú)法運(yùn)行。
- 第一行是每天重置的時(shí)間,格式是hhmmss 示例:032141=03小時(shí)21分鐘41秒
- 第二行是每次倒計(jì)時(shí)使用的時(shí)間,格式hhmmss
- 第三行是日期,用于判斷是否重置日期
- 第四行是驗(yàn)證界面倒計(jì)時(shí),在規(guī)定時(shí)間內(nèi)輸入正確密碼,單位秒
- 第五行是密碼,請(qǐng)記住密碼
- 程序運(yùn)行時(shí)“任務(wù)管理器”“資源監(jiān)視器”無(wú)法使用。
2. 運(yùn)行效果


3.相關(guān)源碼
import tkinter as tk
import time
import os
import logging
import datetime
import comtypes.client
from pycaw.pycaw import AudioUtilities, IAudioEndpointVolume
import psutil
import threading
# 全局標(biāo)志位,用于控制 monitor_and_terminate 線程的終止
stop_monitor_thread = threading.Event()
# 倒計(jì)時(shí)完成驗(yàn)證窗口
class Yanzheng: # 休息窗口
def __init__(self, shi, fen, miao):
# 調(diào)用函數(shù),將 config.txt 作為參數(shù)傳入
self.modify_second_line('config.txt')
toggle_mute()
# 創(chuàng)建主窗口
self.root = tk.Tk()
self.root.title("Countdown Timer")
# 使窗口最大化
self.root.state('zoomed')
# 設(shè)置窗口背景為黑色
self.root.configure(bg='black')
self.root.protocol("WM_DELETE_WINDOW", self.on_close) # 為關(guān)閉窗口協(xié)議指定處理函數(shù) on_close
# 隱藏最小化、最大化和關(guān)閉按鈕
self.root.overrideredirect(True)
# 讓窗口可以拖動(dòng)
self.root.bind('<B1-Motion>', self.move_window)
self.root.attributes('-topmost', True)
# 初始倒計(jì)時(shí)時(shí)間為 2 小時(shí)(秒)
self.shi = shi * 60 * 60
self.fen = fen * 60
self.miao = miao
self.remaining_time = shi * 60 * 60 + fen * 60 + miao
self.password_attempts = 5 # 記錄密碼輸入嘗試次數(shù),初始為 5 次
# 創(chuàng)建一個(gè)標(biāo)簽用于顯示倒計(jì)時(shí)
self.label = tk.Label(self.root, text="休息中...", bg='black', fg='white', font=("Arial", 34))
self.label.pack(expand=True)
# 創(chuàng)建一個(gè)標(biāo)簽用于顯示剩余嘗試次數(shù)
self.attempts_label = tk.Label(self.root, text=f"輸入管理員密碼解除限制,剩余嘗試次數(shù): {self.password_attempts}", bg='black', fg='white', font=("Arial", 18))
self.attempts_label.pack()
self.update_countdown()
# 創(chuàng)建密碼輸入框
self.password_entry = tk.Entry(self.root, show="*")
self.password_entry.pack()
self.password_entry.bind("<Return>", self.check_password)
# 進(jìn)入主事件循環(huán)
self.root.mainloop()
def modify_second_line(self, filename):
try:
with open(filename, 'r') as file:
lines = file.readlines()
if len(lines) >= 2:
lines[1] = '000001\n'
with open(filename, 'w') as file:
file.writelines(lines)
except FileNotFoundError:
print(f"文件 {filename} 未找到")
except Exception as e:
print(f"發(fā)生錯(cuò)誤: {e}")
def on_close(self):
return # 此函數(shù)直接返回,不執(zhí)行任何關(guān)閉操作,從而阻止窗口關(guān)閉
def update_countdown(self):
if self.remaining_time > 0:
# 將剩余時(shí)間轉(zhuǎn)換為 hh:mm:ss 格式
countdown_text = time.strftime('%H:%M:%S', time.gmtime(self.remaining_time))
self.label.config(text=countdown_text)
self.remaining_time -= 1
self.root.after(1000, self.update_countdown) # 每秒更新一次
else:
self.shutdown()
def move_window(self, event):
self.root.geometry(f'+{event.x_root}+{event.y_root}')
def check_password(self, event):
password = self.password_entry.get()
correct_password = mima # 在此處設(shè)置正確的密碼
if password == correct_password:
toggle_mute()
self.root.destroy() # 關(guān)閉窗口,結(jié)束程序
stop_monitor_thread.set() # 設(shè)置標(biāo)志位,通知 monitor_and_terminate 線程終止
thread1.join() # 等待 monitor_and_terminate 線程終止
else:
self.password_attempts -= 1
self.attempts_label.config(text=f"剩余嘗試次數(shù): {self.password_attempts}") # 更新剩余嘗試次數(shù)的顯示
if self.password_attempts <= 0:
self.shutdown()
else:
self.password_entry.delete(0, tk.END) # 清空密碼輸入框
def shutdown(self):
toggle_mute()
os.system("shutdown /s /t 0")
class Daojishi: # 倒計(jì)時(shí)窗口
def __init__(self, shi, fen, miao):
# 創(chuàng)建主窗口
self.root = tk.Tk()
self.root.title("倒計(jì)時(shí)")
self.root.geometry("240x100") # 設(shè)置窗口大小為 240x100
# 設(shè)置窗口背景為黑色
self.root.configure(bg='black')
self.root.protocol("WM_DELETE_WINDOW", self.on_close) # 為關(guān)閉窗口協(xié)議指定處理函數(shù) on_close
# 隱藏最小化、最大化和關(guān)閉按鈕
self.root.overrideredirect(True)
# 讓窗口可以拖動(dòng)
self.root.bind('<B1-Motion>', self.move_window)
# 獲取屏幕的寬度和高度
screen_width = self.root.winfo_screenwidth()
screen_height = self.root.winfo_screenheight()
# 計(jì)算窗口在屏幕中心的位置
x = (screen_width - 240) // 2
y = (screen_height - 100) // 2
# 設(shè)置窗口的位置
self.root.geometry(f"+{x}+{y}")
self.root.attributes('-topmost', True)
# 初始倒計(jì)時(shí)時(shí)間為 2 小時(shí)(秒)
self.shi = shi * 60 * 60
self.fen = fen * 60
self.miao = miao
self.remaining_time = shi * 60 * 60 + fen * 60 + miao
# 創(chuàng)建一個(gè)標(biāo)簽用于顯示倒計(jì)時(shí)
self.label = tk.Label(self.root, text="", bg='black', fg='white', font=('Helvetica', 28))
self.label.pack(expand=True)
# 開(kāi)始倒計(jì)時(shí)
self.start_time = time.time() # 記錄開(kāi)始時(shí)間
self.update_countdown()
# 進(jìn)入主事件循環(huán)
self.root.mainloop()
def on_close(self):
self.root.overrideredirect(False)
self.root.iconify()
self.root.overrideredirect(True)
# 此函數(shù)直接返回,不執(zhí)行任何關(guān)閉操作,從而阻止窗口關(guān)閉
def update_countdown(self):
if self.remaining_time > 0:
# 將剩余時(shí)間轉(zhuǎn)換為 hh:mm:ss 格式
countdown_text = time.strftime('%H:%M:%S', time.gmtime(self.remaining_time))
self.label.config(text=countdown_text)
self.remaining_time -= 1
elapsed_time = time.time() - self.start_time # 計(jì)算經(jīng)過(guò)的時(shí)間
if elapsed_time >= 5: # 每過(guò) 5 秒
self.write_remaining_time_to_file()
self.start_time = time.time() # 重置開(kāi)始時(shí)間
self.root.after(1000, self.update_countdown) # 每秒更新一次
else:
self.root.destroy()
d = Yanzheng(0, 0, yanzhengshijian)
def move_window(self, event):
self.root.geometry(f'+{event.x_root}+{event.y_root}')
def write_remaining_time_to_file(self):
try:
with open('config.txt', 'r+') as config_file:
lines = config_file.readlines()
# 將剩余時(shí)間轉(zhuǎn)換為 hhmmss 格式
remaining_time_hhmmss = time.strftime('%H%M%S', time.gmtime(self.remaining_time))
lines[1] = remaining_time_hhmmss + '\n'
config_file.seek(0)
config_file.writelines(lines)
except FileNotFoundError:
logging.error("config.txt 文件未找到,請(qǐng)檢查文件路徑。")
print("config.txt 文件未找到,請(qǐng)檢查文件路徑。")
# 文件讀取部分
try:
with open('config.txt', 'r',encoding='utf-8') as config_file: # 以只讀模式打開(kāi) config.txt 文件
morenshijian = config_file.readline().strip() # 讀取文件的第一行,默認(rèn)時(shí)間,并去除換行符
shengyushijian = config_file.readline().strip() # 讀取文件的第二行,剩余時(shí)間,并去除換行符
shi = int(shengyushijian[0:2])
fen = int(shengyushijian[2:4])
miao = int(shengyushijian[4:6])
riqi = config_file.readline().strip() # 讀取文件的第三行,日期,并去除換行符
yue = int(riqi[0:2])
ri = int(riqi[2:4])
yanzhengshijian = int(config_file.readline().strip()) # 讀取文件的第四行,驗(yàn)證時(shí)間,并去除換行符
mima = config_file.readline().strip() # 讀取文件的第五行,密碼,并去除換行符
except FileNotFoundError:
logging.error("config.txt 文件未找到,請(qǐng)檢查文件路徑。")
print("config.txt 文件未找到,請(qǐng)檢查文件路徑。")
def xiugai():
try:
with open('config.txt', 'r') as config_file: # 以只讀模式打開(kāi) config.txt 文件
# 跳過(guò)第一行,如果不需要使用第一行的信息
config_file.readline()
gengxinshengyushijian = config_file.readline().strip() # 讀取文件的第二行,剩余時(shí)間,并去除換行符
global gengxinshi, gengxinfen, gengxinmiao
gengxinshi = int(gengxinshengyushijian[0:2])
gengxinfen = int(gengxinshengyushijian[2:4])
gengxinmiao = int(gengxinshengyushijian[4:6])
except FileNotFoundError:
print("config.txt 文件未找到")
return
# 靜音部分
def toggle_mute():
# 獲取系統(tǒng)默認(rèn)音頻設(shè)備
devices = AudioUtilities.GetSpeakers()
interface = devices.Activate(IAudioEndpointVolume._iid_, comtypes.CLSCTX_ALL, None)
volume = comtypes.cast(interface, comtypes.POINTER(IAudioEndpointVolume))
# 檢查當(dāng)前是否靜音
is_muted = volume.GetMute()
if is_muted:
# 如果當(dāng)前是靜音,取消靜音
volume.SetMute(0, None)
else:
# 如果當(dāng)前不是靜音,設(shè)置為靜音
volume.SetMute(1, None)
# 任務(wù)管理器監(jiān)測(cè)部分
def monitor_and_terminate():
target_processes = ["Taskmgr.exe", "perfmon.exe"]
while not stop_monitor_thread.is_set(): # 檢查標(biāo)志位是否被設(shè)置
# 遍歷系統(tǒng)中所有正在運(yùn)行的進(jìn)程
for proc in psutil.process_iter():
try:
# 獲取進(jìn)程名稱
proc_name = proc.name()
# 如果進(jìn)程名稱在目標(biāo)進(jìn)程列表中
if proc_name in target_processes:
# 終止進(jìn)程
proc.terminate()
print(f"Terminated process: {proc_name}")
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
# 處理可能出現(xiàn)的異常
pass
# 休眠 1 秒,避免過(guò)度占用 CPU 資源
time.sleep(1)
# 主程序
def main():
print("主線程啟動(dòng)")
now = datetime.datetime.now()
# 獲取當(dāng)前月份
month = now.month
# 獲取當(dāng)前日期
day = now.day
huoqvriqi = str(month).zfill(2) + str(day).zfill(2)
if month == yue and day == ri:
print("未重置數(shù)據(jù)") # 不更新日期
q = Daojishi(shi, fen, miao)
else:
# 更新日期,更新剩余時(shí)間
# 調(diào)用函數(shù),將 'config.txt' 文件中的第二行替換為變量morenshijian
# 讀取文件內(nèi)容
with open('config.txt', 'r') as file:
lines = file.readlines()
# 檢查文件是否有至少三行
if len(lines) >= 3:
# 修改第二行和第三行
lines[1] = morenshijian + '\n' # 替換第二行內(nèi)容,添加換行符保持格式
lines[2] = huoqvriqi + '\n' # 替換第三行內(nèi)容,添加換行符保持格式
# 將修改后的內(nèi)容寫回文件
with open('config.txt', 'w') as file:
file.writelines(lines)
print("已重置數(shù)據(jù)")
xiugai()
q = Daojishi(gengxinshi, gengxinfen, gengxinmiao)
if __name__ == '__main__':
# 創(chuàng)建線程
thread1 = threading.Thread(target=monitor_and_terminate)
thread3 = threading.Thread(target=main)
# 啟動(dòng)線程
thread1.start()
thread3.start()
# 等待所有線程執(zhí)行完畢
thread1.join()
thread3.join()4.總結(jié)
通過(guò)綜合利用多種技術(shù)(如 tkinter、pycaw、psutil 等),為用戶提供了一個(gè)全面的計(jì)算機(jī)使用時(shí)長(zhǎng)管理解決方案。其主要功能包括倒計(jì)時(shí)管理、音頻控制、密碼驗(yàn)證和系統(tǒng)進(jìn)程監(jiān)控等。這些功能可以幫助用戶管理計(jì)算機(jī)使用時(shí)間并提高工作效率,特別適用于需要定時(shí)休息或防止特定進(jìn)程運(yùn)行的場(chǎng)景。
到此這篇關(guān)于Python實(shí)現(xiàn)計(jì)算機(jī)時(shí)長(zhǎng)管理程序的文章就介紹到這了,更多相關(guān)Python計(jì)算機(jī)時(shí)長(zhǎng)管理內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python深copy和淺copy區(qū)別對(duì)比解析
這篇文章主要介紹了python深copy和淺copy區(qū)別對(duì)比解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-12-12
TensorFlow實(shí)現(xiàn)簡(jiǎn)單線性回歸
這篇文章主要為大家詳細(xì)介紹了TensorFlow實(shí)現(xiàn)簡(jiǎn)單線性回歸,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-03-03
使用Python的PIL庫(kù)給圖像進(jìn)行過(guò)濾
PIL是一個(gè)用于圖像處理的Python庫(kù),它提供了各種功能,包括加載、保存、編輯和處理圖像,你可以使用PIL庫(kù)進(jìn)行圖像縮放、裁剪、旋轉(zhuǎn)、濾鏡應(yīng)用等操作,本文將介紹如何使用Python的PIL庫(kù)給圖像進(jìn)行過(guò)濾,需要的朋友可以參考下2023-08-08
Python類中的裝飾器在當(dāng)前類中的聲明與調(diào)用詳解
這篇文章主要介紹了Python類中的裝飾器在當(dāng)前類中的聲明與調(diào)用詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-04-04
2021年最新用于圖像處理的Python庫(kù)總結(jié)
為了快速地處理大量信息,科學(xué)家需要利用圖像準(zhǔn)備工具來(lái)完成人工智能和深度學(xué)習(xí)任務(wù).在本文中,我將深入研究Python中最有用的圖像處理庫(kù),這些庫(kù)正在人工智能和深度學(xué)習(xí)任務(wù)中得到大力利用.我們開(kāi)始吧,需要的朋友可以參考下2021-06-06
python中django框架通過(guò)正則搜索頁(yè)面上email地址的方法
這篇文章主要介紹了python中django框架通過(guò)正則搜索頁(yè)面上email地址的方法,涉及django框架及正則表達(dá)式的使用技巧,需要的朋友可以參考下2015-03-03
python 快速把超大txt文件轉(zhuǎn)存為csv的實(shí)例
今天小編就為大家分享一篇python 快速把超大txt文件轉(zhuǎn)存為csv的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-10-10
一文學(xué)會(huì)利用python解決文章付費(fèi)限制問(wèn)題
本篇文章主要介紹利用Python爬蟲(chóng)爬取付費(fèi)文章,適合練習(xí)爬蟲(chóng)基礎(chǔ)同學(xué),文中描述和代碼示例很詳細(xì),干貨滿滿,感興趣的小伙伴快來(lái)一起學(xué)習(xí)吧2023-05-05

