1. 简介
这是一个包含倒计时、密码验证、音频控制、系统进程监控与终止等功能的程序。它通过 tkinter 库实现图形用户界面,利用其他模块(如 pycaw 和 psutil)进行系统操作。该程序旨在帮助用户管理计算机使用时长,提供倒计时休息、密码保护解除限制、监控特定进程并通过音频静音管理等功能。
功能:
1.倒计时管理:
用户可以设置倒计时(小时、分钟、秒),并通过窗口实时显示剩余时间。
倒计时结束后,程序自动进行进一步操作,如密码验证或关机。
2.密码验证:
用户可通过输入密码来解除倒计时限制,若输入正确,程序将取消静音并关闭验证窗口。
错误输入密码多次后,程序会执行关机操作。
3.音频控制:
通过 pycaw 库,程序可控制系统音频设备的静音与取消静音。
4.进程监控与终止:
程序在后台监控特定进程(如 taskmgr.exe、perfmon.exe),如果这些进程被检测到,程序会自动终止它们。
5.配置文件管理:
所有关键配置(如初始时间、剩余时间、日期、密码)都存储在 config.txt 文件中,程序在运行时读取和更新该文件,确保数据持续性。
6.系统关机:
如果倒计时结束,或者用户输入密码错误超过设定次数,程序会触发系统关机操作。
注:
- config.txt文件不会自动创建,没有此文件程序会无法运行。
- 第一行是每天重置的时间,格式是hhmmss 示例:032141=03小时21分钟41秒
- 第二行是每次倒计时使用的时间,格式hhmmss
- 第三行是日期,用于判断是否重置日期
- 第四行是验证界面倒计时,在规定时间内输入正确密码,单位秒
- 第五行是密码,请记住密码
- 程序运行时“任务管理器”“资源监视器”无法使用。
2. 运行效果
3.相关源码
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 # 全局标志位,用于控制 monitor_and_terminate 线程的终止 stop_monitor_thread = threading.event() # 倒计时完成验证窗口 class yanzheng: # 休息窗口 def __init__(self, shi, fen, miao): # 调用函数,将 config.txt 作为参数传入 self.modify_second_line('config.txt') toggle_mute() # 创建主窗口 self.root = tk.tk() self.root.title("countdown timer") # 使窗口最大化 self.root.state('zoomed') # 设置窗口背景为黑色 self.root.configure(bg='black') self.root.protocol("wm_delete_window", self.on_close) # 为关闭窗口协议指定处理函数 on_close # 隐藏最小化、最大化和关闭按钮 self.root.overrideredirect(true) # 让窗口可以拖动 self.root.bind('<b1-motion>', self.move_window) self.root.attributes('-topmost', true) # 初始倒计时时间为 2 小时(秒) 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 # 记录密码输入尝试次数,初始为 5 次 # 创建一个标签用于显示倒计时 self.label = tk.label(self.root, text="休息中...", bg='black', fg='white', font=("arial", 34)) self.label.pack(expand=true) # 创建一个标签用于显示剩余尝试次数 self.attempts_label = tk.label(self.root, text=f"输入管理员密码解除限制,剩余尝试次数: {self.password_attempts}", bg='black', fg='white', font=("arial", 18)) self.attempts_label.pack() self.update_countdown() # 创建密码输入框 self.password_entry = tk.entry(self.root, show="*") self.password_entry.pack() self.password_entry.bind("<return>", self.check_password) # 进入主事件循环 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"发生错误: {e}") def on_close(self): return # 此函数直接返回,不执行任何关闭操作,从而阻止窗口关闭 def update_countdown(self): if self.remaining_time > 0: # 将剩余时间转换为 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 # 在此处设置正确的密码 if password == correct_password: toggle_mute() self.root.destroy() # 关闭窗口,结束程序 stop_monitor_thread.set() # 设置标志位,通知 monitor_and_terminate 线程终止 thread1.join() # 等待 monitor_and_terminate 线程终止 else: self.password_attempts -= 1 self.attempts_label.config(text=f"剩余尝试次数: {self.password_attempts}") # 更新剩余尝试次数的显示 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: # 倒计时窗口 def __init__(self, shi, fen, miao): # 创建主窗口 self.root = tk.tk() self.root.title("倒计时") self.root.geometry("240x100") # 设置窗口大小为 240x100 # 设置窗口背景为黑色 self.root.configure(bg='black') self.root.protocol("wm_delete_window", self.on_close) # 为关闭窗口协议指定处理函数 on_close # 隐藏最小化、最大化和关闭按钮 self.root.overrideredirect(true) # 让窗口可以拖动 self.root.bind('<b1-motion>', self.move_window) # 获取屏幕的宽度和高度 screen_width = self.root.winfo_screenwidth() screen_height = self.root.winfo_screenheight() # 计算窗口在屏幕中心的位置 x = (screen_width - 240) // 2 y = (screen_height - 100) // 2 # 设置窗口的位置 self.root.geometry(f"+{x}+{y}") self.root.attributes('-topmost', true) # 初始倒计时时间为 2 小时(秒) self.shi = shi * 60 * 60 self.fen = fen * 60 self.miao = miao self.remaining_time = shi * 60 * 60 + fen * 60 + miao # 创建一个标签用于显示倒计时 self.label = tk.label(self.root, text="", bg='black', fg='white', font=('helvetica', 28)) self.label.pack(expand=true) # 开始倒计时 self.start_time = time.time() # 记录开始时间 self.update_countdown() # 进入主事件循环 self.root.mainloop() def on_close(self): self.root.overrideredirect(false) self.root.iconify() self.root.overrideredirect(true) # 此函数直接返回,不执行任何关闭操作,从而阻止窗口关闭 def update_countdown(self): if self.remaining_time > 0: # 将剩余时间转换为 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 # 计算经过的时间 if elapsed_time >= 5: # 每过 5 秒 self.write_remaining_time_to_file() self.start_time = time.time() # 重置开始时间 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() # 将剩余时间转换为 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 文件未找到,请检查文件路径。") print("config.txt 文件未找到,请检查文件路径。") # 文件读取部分 try: with open('config.txt', 'r',encoding='utf-8') as config_file: # 以只读模式打开 config.txt 文件 morenshijian = config_file.readline().strip() # 读取文件的第一行,默认时间,并去除换行符 shengyushijian = config_file.readline().strip() # 读取文件的第二行,剩余时间,并去除换行符 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()) # 读取文件的第四行,验证时间,并去除换行符 mima = config_file.readline().strip() # 读取文件的第五行,密码,并去除换行符 except filenotfounderror: logging.error("config.txt 文件未找到,请检查文件路径。") print("config.txt 文件未找到,请检查文件路径。") def xiugai(): try: with open('config.txt', 'r') as config_file: # 以只读模式打开 config.txt 文件 # 跳过第一行,如果不需要使用第一行的信息 config_file.readline() gengxinshengyushijian = config_file.readline().strip() # 读取文件的第二行,剩余时间,并去除换行符 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(): # 获取系统默认音频设备 devices = audioutilities.getspeakers() interface = devices.activate(iaudioendpointvolume._iid_, comtypes.clsctx_all, none) volume = comtypes.cast(interface, comtypes.pointer(iaudioendpointvolume)) # 检查当前是否静音 is_muted = volume.getmute() if is_muted: # 如果当前是静音,取消静音 volume.setmute(0, none) else: # 如果当前不是静音,设置为静音 volume.setmute(1, none) # 任务管理器监测部分 def monitor_and_terminate(): target_processes = ["taskmgr.exe", "perfmon.exe"] while not stop_monitor_thread.is_set(): # 检查标志位是否被设置 # 遍历系统中所有正在运行的进程 for proc in psutil.process_iter(): try: # 获取进程名称 proc_name = proc.name() # 如果进程名称在目标进程列表中 if proc_name in target_processes: # 终止进程 proc.terminate() print(f"terminated process: {proc_name}") except (psutil.nosuchprocess, psutil.accessdenied, psutil.zombieprocess): # 处理可能出现的异常 pass # 休眠 1 秒,避免过度占用 cpu 资源 time.sleep(1) # 主程序 def main(): print("主线程启动") now = datetime.datetime.now() # 获取当前月份 month = now.month # 获取当前日期 day = now.day huoqvriqi = str(month).zfill(2) + str(day).zfill(2) if month == yue and day == ri: print("未重置数据") # 不更新日期 q = daojishi(shi, fen, miao) else: # 更新日期,更新剩余时间 # 调用函数,将 'config.txt' 文件中的第二行替换为变量morenshijian # 读取文件内容 with open('config.txt', 'r') as file: lines = file.readlines() # 检查文件是否有至少三行 if len(lines) >= 3: # 修改第二行和第三行 lines[1] = morenshijian + '\n' # 替换第二行内容,添加换行符保持格式 lines[2] = huoqvriqi + '\n' # 替换第三行内容,添加换行符保持格式 # 将修改后的内容写回文件 with open('config.txt', 'w') as file: file.writelines(lines) print("已重置数据") xiugai() q = daojishi(gengxinshi, gengxinfen, gengxinmiao) if __name__ == '__main__': # 创建线程 thread1 = threading.thread(target=monitor_and_terminate) thread3 = threading.thread(target=main) # 启动线程 thread1.start() thread3.start() # 等待所有线程执行完毕 thread1.join() thread3.join()
4.总结
通过综合利用多种技术(如 tkinter、pycaw、psutil 等),为用户提供了一个全面的计算机使用时长管理解决方案。其主要功能包括倒计时管理、音频控制、密码验证和系统进程监控等。这些功能可以帮助用户管理计算机使用时间并提高工作效率,特别适用于需要定时休息或防止特定进程运行的场景。
到此这篇关于python实现计算机时长管理程序的文章就介绍到这了,更多相关python计算机时长管理内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论