林又新 發表於 2026-1-9 08:58:01

Python设置电脑定时关机的方法详解(附完整代码)

<div id="navCategory"><h5 class="catalogue">目录</h5><ul class="first_class_ul"><li><a href="#_label0">方法一:使用 Windows 自带的命令(最简单通用)</a></li><li><a href="#_label1">方法二:创建定时关机的快捷方式(一键启动)</a></li><li><a href="#_label2">方法三:使用任务计划程序(精确到具体日期和时间)</a></li><li><a href="#_label3">方法四:python代码实现</a></li><ul class="second_class_ul"><li><a href="#_lab2_3_0">实现代码</a></li><li><a href="#_lab2_3_1">功能说明</a></li><li><a href="#_lab2_3_2">使用说明</a></li></ul><li><a href="#_label4">重要提醒</a></li><ul class="second_class_ul"></ul></ul></div><p>为电脑设置定时关机有多种方法,从简单到高级,您可以根据自己的需求选择。</p>
<p class="maodian"><a name="_label0"></a></p><h2>方法一:使用 Windows 自带的命令(最简单通用)</h2>
<p>这是最经典、最灵活的方法,适用于所有 Windows 系统。</p>
<p><strong>1.打开&ldquo;运行&rdquo;对话框</strong>:</p>
<ul><li>按键盘上的 <code>Win</code> + <code>R</code> 键。</li><li>或者在开始菜单搜索&ldquo;运行&rdquo;。</li></ul>
<p><strong>2.输入关机命令</strong>:</p>
<p>在打开的运行框中,输入以下命令:</p>
<blockquote><p>shutdown -s -t 秒数</p></blockquote>
<p><code>shutdown</code>:关机命令。</p>
<p><code>-s</code>:表示关闭计算机。</p>
<p><code>-t</code>:后面跟延迟时间。</p>
<p><code>秒数</code>:指定多少秒后关机。例如:</p>
<ul><li>1小时后关机:<code>shutdown -s -t 3600</code> (1小时 = 60分钟 &times; 60秒)</li><li>2小时后关机:<code>shutdown -s -t 7200</code></li><li>30分钟后关机:<code>shutdown -s -t 1800</code></li><li>晚上11点关机(假设现在晚上10点):<code>shutdown -s -t 3600</code></li></ul>
<p><strong>3.执行命令</strong>:</p>
<ul><li>点击&ldquo;确定&rdquo;或按回车键。</li><li>成功后会弹出一个小窗口提示&ldquo;Windows 将在 XX 分钟后关闭&rdquo;。</li></ul>
<p><strong>如何取消定时关机?</strong></p>
<p>同样打开&ldquo;运行&rdquo; (<code>Win + R</code>),输入:</p>
<div class="jb51code"><pre class="brush:bash;">shutdown -a
</pre></div>
<p>按回车。系统会提示&ldquo;计划的关闭已取消&rdquo;。</p>
<p class="maodian"><a name="_label1"></a></p><h2>方法二:创建定时关机的快捷方式(一键启动)</h2>
<p>如果您需要频繁使用某个固定的时间(如下载大文件常用2小时),可以创建一个桌面快捷方式。</p>
<ul><li>在桌面空白处点击右键,选择 <strong>新建 -&gt; 快捷方式</strong>。</li><li>在&ldquo;请输入对象的位置&rdquo;框中,输入命令,例如: shutdown -s -t 7200 (这里以2小时/7200秒为例)</li><li>点击 <strong>下一步</strong>,为这个快捷方式起个名字,例如&ldquo;2小时后关机&rdquo;。</li><li>点击 <strong>完成</strong>。</li></ul>
<p>现在,只需双击这个桌面图标,就会启动2小时后关机的命令。</p>
<p class="maodian"><a name="_label2"></a></p><h2>方法三:使用任务计划程序(精确到具体日期和时间)</h2>
<p>如果你想要像设置闹钟一样,让电脑在<strong>每天晚上11点</strong>或<strong>每周五下午5点</strong>自动关机,这是最专业的方法。</p>
<ol><li>在开始菜单搜索并打开 <strong>&ldquo;任务计划程序&rdquo;</strong>。</li><li>在右侧操作栏,点击 <strong>&ldquo;创建基本任务&rdquo;</strong>。</li><li><strong>设置名称和描述</strong>:例如&ldquo;每日自动关机&rdquo;,点击下一步。</li><li><strong>选择触发器</strong>:选择&ldquo;每天&rdquo;、&ldquo;每周&rdquo;或&ldquo;一次&rdquo;,点击下一步。<ul><li>如果选&ldquo;每天&rdquo;,设置开始日期和具体时间(如23:00)。</li></ul></li><li><strong>选择操作</strong>:选择&ldquo;启动程序&rdquo;,点击下一步。</li><li><strong>设置程序或脚本</strong>:<ul><li>在&ldquo;程序或脚本&rdquo;框中输入:<code>shutdown</code></li><li>在&ldquo;添加参数&rdquo;框中输入:<code>-s -f</code> (<code>-f</code> 表示强制关闭正在运行的应用程序)</li><li><strong>注意</strong>:这里不需要 <code>-t</code> 参数,因为触发时间由任务计划控制。</li></ul></li><li>点击下一步,然后完成。</li></ol>
<p>这样,电脑就会在你设定的周期和时间点自动关机。</p>
<p class="maodian"><a name="_label3"></a></p><h2>方法四:python代码实现</h2>
<p style="text-align:center"><img alt="" src="https://img.jbzj.com/file_images/article/202601/2026010908562858.gif" /></p>
<p class="maodian"><a name="_lab2_3_0"></a></p><h3>实现代码</h3>
<p>下面是一个使用 Python tkinter 实现前三种定时关机方法的完整程序:</p>
<div class="jb51code"><pre class="brush:py;">import tkinter as tk
from tkinter import ttk, messagebox
import os
import time
import subprocess
import threading
from datetime import datetime, timedelta

class ShutdownTimerApp:
    def __init__(self, root):
      self.root = root
      self.root.title("定时关机工具 v1.0")
      self.root.geometry("600x500")
      
      # 设置样式
      self.setup_styles()
      
      # 创建主界面
      self.create_widgets()
      
      # 存储定时任务线程
      self.shutdown_thread = None
      self.is_scheduled = False
      
    def setup_styles(self):
      """设置界面样式"""
      style = ttk.Style()
      style.configure('Title.TLabel', font=('微软雅黑', 16, 'bold'))
      style.configure('Method.TLabelframe.Label', font=('微软雅黑', 11, 'bold'))
      style.configure('Large.TButton', font=('微软雅黑', 10))
      
    def create_widgets(self):
      """创建界面组件"""
      # 标题
      title_label = ttk.Label(self.root, text="定时关机工具", style='Title.TLabel')
      title_label.pack(pady=20)
      
      # 创建笔记本控件(选项卡)
      self.notebook = ttk.Notebook(self.root)
      self.notebook.pack(fill='both', expand=True, padx=20, pady=10)
      
      # 方法一:使用命令
      self.create_method1_tab()
      
      # 方法二:快捷方式
      self.create_method2_tab()
      
      # 方法三:任务计划(简化版)
      self.create_method3_tab()
      
      # 状态栏
      self.create_status_bar()
      
    def create_method1_tab(self):
      """创建方法一选项卡:使用命令"""
      frame = ttk.Frame(self.notebook)
      self.notebook.add(frame, text="方法一:命令行设置")
      
      # 说明标签
      desc = "通过Windows shutdown命令设置定时关机\n支持设置任意秒数后关机"
      desc_label = ttk.Label(frame, text=desc, font=('微软雅黑', 10))
      desc_label.pack(pady=10)
      
      # 时间设置区域
      time_frame = ttk.LabelFrame(frame, text="设置关机时间", style='Method.TLabelframe')
      time_frame.pack(fill='x', padx=20, pady=10)
      
      # 预设时间按钮
      preset_frame = ttk.Frame(time_frame)
      preset_frame.pack(pady=10)
      
      preset_times = [
            ("30分钟后", 1800),
            ("1小时后", 3600),
            ("2小时后", 7200),
            ("3小时后", 10800),
            ("5分钟后", 300)
      ]
      
      for text, seconds in preset_times:
            btn = ttk.Button(preset_frame, text=text,
                           command=lambda s=seconds: self.set_custom_time(s))
            btn.pack(side='left', padx=5)
      
      # 自定义时间输入
      custom_frame = ttk.Frame(time_frame)
      custom_frame.pack(pady=10)
      
      ttk.Label(custom_frame, text="自定义时间:").pack(side='left')
      
      self.hour_var = tk.StringVar(value="0")
      hour_spin = ttk.Spinbox(custom_frame, from_=0, to=23, width=5,
                               textvariable=self.hour_var)
      hour_spin.pack(side='left', padx=5)
      ttk.Label(custom_frame, text="小时").pack(side='left')
      
      self.minute_var = tk.StringVar(value="30")
      minute_spin = ttk.Spinbox(custom_frame, from_=0, to=59, width=5,
                                 textvariable=self.minute_var)
      minute_spin.pack(side='left', padx=5)
      ttk.Label(custom_frame, text="分钟").pack(side='left')
      
      # 命令预览区域
      preview_frame = ttk.LabelFrame(frame, text="命令预览", style='Method.TLabelframe')
      preview_frame.pack(fill='x', padx=20, pady=10)
      
      self.command_var = tk.StringVar()
      command_label = ttk.Label(preview_frame, textvariable=self.command_var,
                                 font=('Consolas', 10))
      command_label.pack(pady=10)
      
      # 按钮区域
      button_frame = ttk.Frame(frame)
      button_frame.pack(pady=20)
      
      self.set_btn1 = ttk.Button(button_frame, text="设置定时关机",
                                  command=self.set_shutdown_cmd, style='Large.TButton')
      self.set_btn1.pack(side='left', padx=10)
      
      self.cancel_btn1 = ttk.Button(button_frame, text="取消定时关机",
                                     command=self.cancel_shutdown_cmd, style='Large.TButton')
      self.cancel_btn1.pack(side='left', padx=10)
      
      # 更新命令预览
      self.update_command_preview()
      
    def create_method2_tab(self):
      """创建方法二选项卡:快捷方式"""
      frame = ttk.Frame(self.notebook)
      self.notebook.add(frame, text="方法二:创建快捷方式")
      
      # 说明标签
      desc = "为常用关机时间创建桌面快捷方式\n双击即可启动定时关机"
      desc_label = ttk.Label(frame, text=desc, font=('微软雅黑', 10))
      desc_label.pack(pady=10)
      
      # 快捷方式设置
      shortcut_frame = ttk.LabelFrame(frame, text="快捷方式设置", style='Method.TLabelframe')
      shortcut_frame.pack(fill='x', padx=20, pady=10)
      
      # 快捷方式名称
      name_frame = ttk.Frame(shortcut_frame)
      name_frame.pack(pady=10, anchor='w', padx=20)
      
      ttk.Label(name_frame, text="快捷方式名称:").pack(side='left')
      self.shortcut_name = tk.StringVar(value="定时关机")
      name_entry = ttk.Entry(name_frame, textvariable=self.shortcut_name, width=30)
      name_entry.pack(side='left', padx=10)
      
      # 关机时间设置
      time_frame = ttk.Frame(shortcut_frame)
      time_frame.pack(pady=10, anchor='w', padx=20)
      
      ttk.Label(time_frame, text="关机时间:").pack(side='left')
      
      self.shortcut_hours = tk.StringVar(value="1")
      hour_spin = ttk.Spinbox(time_frame, from_=0, to=23, width=3,
                               textvariable=self.shortcut_hours)
      hour_spin.pack(side='left', padx=5)
      ttk.Label(time_frame, text="小时").pack(side='left')
      
      self.shortcut_minutes = tk.StringVar(value="0")
      minute_spin = ttk.Spinbox(time_frame, from_=0, to=59, width=3,
                                 textvariable=self.shortcut_minutes)
      minute_spin.pack(side='left', padx=5)
      ttk.Label(time_frame, text="分钟").pack(side='left')
      
      # 快捷方式内容预览
      preview_frame = ttk.LabelFrame(frame, text="快捷方式内容", style='Method.TLabelframe')
      preview_frame.pack(fill='x', padx=20, pady=10)
      
      self.shortcut_content = tk.Text(preview_frame, height=4, font=('Consolas', 9))
      self.shortcut_content.pack(pady=10, padx=10, fill='x')
      self.shortcut_content.insert('1.0', "shutdown -s -t 3600")
      self.shortcut_content.config(state='disabled')
      
      # 按钮区域
      button_frame = ttk.Frame(frame)
      button_frame.pack(pady=20)
      
      create_btn = ttk.Button(button_frame, text="创建桌面快捷方式",
                               command=self.create_shortcut, style='Large.TButton')
      create_btn.pack(side='left', padx=10)
      
      test_btn = ttk.Button(button_frame, text="测试此时间设置",
                           command=self.test_shortcut_time, style='Large.TButton')
      test_btn.pack(side='left', padx=10)
      
      # 绑定变量变化事件
      self.shortcut_hours.trace('w', self.update_shortcut_preview)
      self.shortcut_minutes.trace('w', self.update_shortcut_preview)
      
    def create_method3_tab(self):
      """创建方法三选项卡:任务计划(简化版)"""
      frame = ttk.Frame(self.notebook)
      self.notebook.add(frame, text="方法三:定时任务")
      
      # 说明标签
      desc = "设置每天固定时间自动关机\n适合规律性定时关机需求"
      desc_label = ttk.Label(frame, text=desc, font=('微软雅黑', 10))
      desc_label.pack(pady=10)
      
      # 时间设置
      schedule_frame = ttk.LabelFrame(frame, text="定时设置", style='Method.TLabelframe')
      schedule_frame.pack(fill='x', padx=20, pady=10)
      
      # 时间选择
      time_frame = ttk.Frame(schedule_frame)
      time_frame.pack(pady=15, anchor='center')
      
      ttk.Label(time_frame, text="每天关机时间:", font=('微软雅黑', 10)).pack(side='left')
      
      self.schedule_hour = tk.StringVar(value="22")
      hour_spin = ttk.Spinbox(time_frame, from_=0, to=23, width=3,
                               textvariable=self.schedule_hour)
      hour_spin.pack(side='left', padx=5)
      ttk.Label(time_frame, text=":").pack(side='left')
      
      self.schedule_minute = tk.StringVar(value="00")
      minute_spin = ttk.Spinbox(time_frame, from_=0, to=59, width=3,
                                 textvariable=self.schedule_minute)
      minute_spin.pack(side='left', padx=5)
      
      # 任务状态显示
      self.task_status_var = tk.StringVar(value="当前无定时任务")
      status_label = ttk.Label(schedule_frame, textvariable=self.task_status_var,
                              font=('微软雅黑', 9))
      status_label.pack(pady=10)
      
      # 计算下次关机时间
      self.next_time_var = tk.StringVar()
      next_time_label = ttk.Label(schedule_frame, textvariable=self.next_time_var,
                                 font=('微软雅黑', 9))
      next_time_label.pack(pady=5)
      
      # 模拟任务区域
      sim_frame = ttk.LabelFrame(frame, text="模拟任务管理", style='Method.TLabelframe')
      sim_frame.pack(fill='x', padx=20, pady=10)
      
      sim_desc = """注意:这是简化版模拟定时任务。
真实的Windows任务计划需要管理员权限和复杂配置。
本程序使用Python线程模拟定时功能。"""
      sim_label = ttk.Label(sim_frame, text=sim_desc, font=('微软雅黑', 9))
      sim_label.pack(pady=10, padx=10)
      
      # 按钮区域
      button_frame = ttk.Frame(frame)
      button_frame.pack(pady=20)
      
      self.schedule_btn = ttk.Button(button_frame, text="启动定时任务",
                                    command=self.toggle_schedule, style='Large.TButton')
      self.schedule_btn.pack(side='left', padx=10)
      
      ttk.Button(button_frame, text="立即测试关机",
                  command=self.test_schedule_shutdown, style='Large.TButton').pack(side='left', padx=10)
      
    def create_status_bar(self):
      """创建状态栏"""
      status_frame = ttk.Frame(self.root)
      status_frame.pack(fill='x', side='bottom', pady=5)
      
      self.status_var = tk.StringVar(value="就绪")
      status_label = ttk.Label(status_frame, textvariable=self.status_var,
                              relief='sunken', anchor='w')
      status_label.pack(fill='x', padx=10, pady=2)
      
    def set_custom_time(self, seconds):
      """设置自定义时间到输入框"""
      hours = seconds // 3600
      minutes = (seconds % 3600) // 60
      
      self.hour_var.set(str(hours))
      self.minute_var.set(str(minutes))
      self.update_command_preview()
      
    def update_command_preview(self, *args):
      """更新命令预览"""
      try:
            hours = int(self.hour_var.get() or 0)
            minutes = int(self.minute_var.get() or 0)
            seconds = hours * 3600 + minutes * 60
            
            if seconds &gt; 0:
                self.command_var.set(f"shutdown -s -t {seconds}")
            else:
                self.command_var.set("请设置有效的关机时间")
      except ValueError:
            self.command_var.set("请输入有效数字")
            
    def update_shortcut_preview(self, *args):
      """更新快捷方式内容预览"""
      try:
            hours = int(self.shortcut_hours.get() or 0)
            minutes = int(self.shortcut_minutes.get() or 0)
            seconds = hours * 3600 + minutes * 60
            
            if seconds &gt; 0:
                content = f"shutdown -s -t {seconds}"
                self.shortcut_content.config(state='normal')
                self.shortcut_content.delete('1.0', 'end')
                self.shortcut_content.insert('1.0', content)
                self.shortcut_content.config(state='disabled')
      except ValueError:
            pass
            
    def set_shutdown_cmd(self):
      """执行方法一:设置关机命令"""
      try:
            hours = int(self.hour_var.get() or 0)
            minutes = int(self.minute_var.get() or 0)
            seconds = hours * 3600 + minutes * 60
            
            if seconds &lt;= 0:
                messagebox.showwarning("警告", "请设置有效的关机时间")
                return
               
            # 执行关机命令
            subprocess.run(f"shutdown -s -t {seconds}", shell=True)
            
            # 计算关机时间
            shutdown_time = datetime.now() + timedelta(seconds=seconds)
            
            messagebox.showinfo("成功",
                f"定时关机已设置!\n"
                f"系统将在 {hours}小时{minutes}分钟后关闭\n"
                f"预计关机时间:{shutdown_time.strftime('%Y-%m-%d %H:%M:%S')}\n\n"
                f"如需取消,请使用取消按钮或运行命令:shutdown -a")
            
            self.status_var.set(f"已设置 {hours}小时{minutes}分钟后关机")
            
      except ValueError:
            messagebox.showerror("错误", "请输入有效的数字")
      except Exception as e:
            messagebox.showerror("错误", f"设置失败:{str(e)}")
            
    def cancel_shutdown_cmd(self):
      """取消定时关机"""
      try:
            subprocess.run("shutdown -a", shell=True)
            messagebox.showinfo("成功", "定时关机已取消")
            self.status_var.set("定时关机已取消")
      except Exception as e:
            messagebox.showerror("错误", f"取消失败:{str(e)}")
            
    def create_shortcut(self):
      """创建桌面快捷方式"""
      try:
            # 获取桌面路径
            desktop_path = os.path.join(os.path.expanduser('~'), 'Desktop')
            
            # 计算秒数
            hours = int(self.shortcut_hours.get() or 0)
            minutes = int(self.shortcut_minutes.get() or 0)
            seconds = hours * 3600 + minutes * 60
            
            if seconds &lt;= 0:
                messagebox.showwarning("警告", "请设置有效的关机时间")
                return
               
            # 创建批处理文件
            bat_content = f"""@echo off
echo 正在设置定时关机...
echo 系统将在 {hours}小时{minutes}分钟后关闭
shutdown -s -t {seconds}
pause
"""
            
            # 创建快捷方式内容(VBS脚本)
            shortcut_name = self.shortcut_name.get() or "定时关机"
            bat_filename = f"{shortcut_name}.bat"
            bat_path = os.path.join(desktop_path, bat_filename)
            
            vbs_content = f"""Set WshShell = CreateObject("WScript.Shell")
Set oShellLink = WshShell.CreateShortcut("{desktop_path}\\{shortcut_name}.lnk")
oShellLink.TargetPath = "{bat_path}"
oShellLink.WindowStyle = 1
oShellLink.Description = "定时关机快捷方式"
oShellLink.Save
"""
            
            # 保存批处理文件
            with open(bat_path, 'w', encoding='gbk') as f:
                f.write(bat_content)
               
            # 保存VBS脚本并创建快捷方式
            vbs_path = os.path.join(desktop_path, "create_shortcut.vbs")
            with open(vbs_path, 'w', encoding='gbk') as f:
                f.write(vbs_content)
               
            subprocess.run(f'cscript //nologo "{vbs_path}"', shell=True)
            
            # 清理临时文件
            os.remove(vbs_path)
            
            messagebox.showinfo("成功",
                f"快捷方式已创建到桌面!\n"
                f"文件名:{shortcut_name}.lnk\n"
                f"双击即可设置 {hours}小时{minutes}分钟后关机")
            
            self.status_var.set(f"快捷方式已创建:{shortcut_name}")
            
      except Exception as e:
            messagebox.showerror("错误", f"创建失败:{str(e)}")
            
    def test_shortcut_time(self):
      """测试快捷方式设置的关机时间"""
      try:
            hours = int(self.shortcut_hours.get() or 0)
            minutes = int(self.shortcut_minutes.get() or 0)
            seconds = hours * 3600 + minutes * 60
            
            if seconds &lt;= 0:
                messagebox.showwarning("警告", "请设置有效的关机时间")
                return
               
            subprocess.run(f"shutdown -s -t {seconds}", shell=True)
            
            messagebox.showinfo("测试成功",
                f"已设置测试关机!\n"
                f"系统将在 {hours}小时{minutes}分钟后关闭\n"
                f"如需取消请使用'取消定时关机'按钮")
            
      except Exception as e:
            messagebox.showerror("错误", f"测试失败:{str(e)}")
            
    def toggle_schedule(self):
      """启动/停止定时任务"""
      if not self.is_scheduled:
            try:
                hour = int(self.schedule_hour.get() or 22)
                minute = int(self.schedule_minute.get() or 0)
               
                if hour &lt; 0 or hour &gt; 23 or minute &lt; 0 or minute &gt; 59:
                  messagebox.showwarning("警告", "请输入有效的时间")
                  return
                  
                # 启动定时任务线程
                self.shutdown_thread = threading.Thread(
                  target=self.schedule_shutdown_task,
                  args=(hour, minute),
                  daemon=True
                )
                self.shutdown_thread.start()
               
                self.is_scheduled = True
                self.schedule_btn.config(text="停止定时任务")
               
                # 更新状态显示
                now = datetime.now()
                target_time = datetime(now.year, now.month, now.day, hour, minute)
                if target_time &lt; now:
                  target_time += timedelta(days=1)
                  
                self.task_status_var.set(f"定时任务已启动")
                self.next_time_var.set(f"下次关机时间:{target_time.strftime('%Y-%m-%d %H:%M')}")
               
                messagebox.showinfo("成功",
                  f"定时任务已启动!\n"
                  f"每天 {hour:02d}:{minute:02d} 自动关机\n"
                  f"注意:这是程序模拟的定时任务,关闭本程序将停止")
               
                self.status_var.set(f"定时任务已启动:每天 {hour:02d}:{minute:02d}")
               
            except ValueError:
                messagebox.showerror("错误", "请输入有效数字")
      else:
            # 停止定时任务
            self.is_scheduled = False
            self.schedule_btn.config(text="启动定时任务")
            self.task_status_var.set("定时任务已停止")
            self.next_time_var.set("")
            self.status_var.set("定时任务已停止")
            
    def schedule_shutdown_task(self, target_hour, target_minute):
      """定时任务线程函数"""
      while self.is_scheduled:
            try:
                now = datetime.now()
               
                # 计算今天的目标时间
                target_time = datetime(now.year, now.month, now.day, target_hour, target_minute)
               
                # 如果今天的时间已过,设置为明天
                if target_time &lt; now:
                  target_time += timedelta(days=1)
               
                # 计算等待时间(秒)
                wait_seconds = (target_time - now).total_seconds()
               
                # 每隔10秒检查一次,以便及时响应停止命令
                for _ in range(int(wait_seconds / 10)):
                  if not self.is_scheduled:
                        return
                  time.sleep(10)
               
                # 等待剩余时间
                remaining = wait_seconds % 10
                if remaining &gt; 0 and self.is_scheduled:
                  time.sleep(remaining)
               
                # 执行关机
                if self.is_scheduled:
                  subprocess.run("shutdown -s -t 60", shell=True)
                  
                  # 更新状态
                  self.root.after(0, lambda: self.task_status_var.set(
                        f"已执行关机命令!下次将在明天 {target_hour:02d}:{target_minute:02d}"))
                  
                  # 重置为明天
                  time.sleep(65)# 等待关机执行时间
                  
            except Exception as e:
                print(f"定时任务错误:{e}")
                break
               
    def test_schedule_shutdown(self):
      """测试定时关机(立即关机,但给予取消时间)"""
      response = messagebox.askyesno("确认测试",
            "将设置60秒后关机进行测试\n请确保已保存所有工作\n\n是否继续?")
      
      if response:
            subprocess.run("shutdown -s -t 60", shell=True)
            messagebox.showinfo("测试开始",
                "已设置60秒后关机\n"
                "如需取消请使用'取消定时关机'按钮")
            self.status_var.set("测试关机已设置:60秒后关闭")

def main():
    root = tk.Tk()
    app = ShutdownTimerApp(root)
    root.mainloop()

if __name__ == "__main__":
    main()
</pre></div>
<p class="maodian"><a name="_lab2_3_1"></a></p><h3>功能说明</h3>
<p><strong>方法一:命令行设置</strong></p>
<ul><li>提供预设时间按钮(5分钟、30分钟、1小时等)</li><li>支持自定义小时和分钟设置</li><li>实时显示将要执行的命令</li><li>设置和取消按钮</li></ul>
<p><strong>方法二:创建快捷方式</strong></p>
<ul><li>自定义快捷方式名称</li><li>设置关机时间</li><li>预览快捷方式内容</li><li>创建桌面快捷方式</li><li>测试快捷方式功能</li></ul>
<p><strong>方法三:定时任务(简化版)</strong></p>
<ul><li>设置每天固定时间自动关机</li><li>模拟Windows任务计划功能</li><li>显示下次关机时间</li><li>启动/停止定时任务</li><li>测试功能</li></ul>
<p class="maodian"><a name="_lab2_3_2"></a></p><h3>使用说明</h3>
<p><strong>运行程序</strong>:</p>
<div class="jb51code"><pre class="brush:bash;">python shutdown_timer.py
</pre></div>
<p><strong>注意事项</strong>:</p>
<ul><li>程序需要Windows系统支持</li><li>方法三为Python模拟实现,关闭程序会停止定时任务</li><li>真实的Windows任务计划需要管理员权限和更复杂的配置</li></ul>
<p><strong>安全提醒</strong>:</p>
<ul><li>定时关机前请保存好所有工作</li><li>测试时建议设置较短时间(如5分钟)</li><li>记住可以使用<code>shutdown -a</code>命令或程序的取消功能</li></ul>
<p class="maodian"><a name="_label4"></a></p><h2>重要提醒</h2>
<ul><li><strong>保存工作</strong>:在设置自动关机前,请务必保存好所有打开的文件和工作进度,防止数据丢失。</li><li><strong>取消命令</strong>:记住取消命令 <code>shutdown -a</code>,或者去任务计划程序里禁用任务,以备不时之需。</li></ul>
<p><strong>总结建议</strong>:</p>
<ul><li><strong>临时用一次</strong>:用 <strong>方法一</strong> 运行命令。</li><li><strong>经常固定时间用</strong>:用 <strong>方法二</strong> 创建快捷方式。</li><li><strong>长期规律性定时</strong>:用 <strong>方法三</strong> 任务计划程序。</li><li><strong>怕麻烦,喜欢点鼠标</strong>:用 <strong>方法四</strong> 第三方软件。</li></ul>
<p>选择最适合你的方法即可!</p>
頁: [1]
查看完整版本: Python设置电脑定时关机的方法详解(附完整代码)