[Python急救站]定时关机程序

发布时间 2024-01-10 22:11:03作者: Jinylin

收到朋友的请求,让我帮他做一个电脑关机程序,其实非常简单。代码如下:

import tkinter as tk  # 导入tkinter模块
from tkinter import ttk  # 导入ttk模块
import subprocess  # 导入subprocess模块


def shutdown():
    hours = hour_entry.get()  # 获取时的填空中的值
    minutes = minute_entry.get()  # 获取分的填空中的值
    seconds = second_entry.get()  # 获取秒的填空中的值

    try:
        hours = int(hours)  # 将时转换为整数
        minutes = int(minutes)  # 将分转换为整数
        seconds = int(seconds)  # 将秒转换为整数

        total_seconds = hours * 3600 + minutes * 60 + seconds  # 计算总秒数

        if total_seconds <= 0:  # 如果总秒数小于等于0
            raise ValueError  # 抛出值错误

        subprocess.run(f"shutdown -s -t {total_seconds}")  # 执行关机命令
        label.config(text="计算机将在{}秒后关机".format(total_seconds))  # 更新标签文本
    except ValueError:
        label.config(text="请输入一个有效的时间")  # 更新标签文本


# 创建窗口
window = tk.Tk()  # 创建Tk窗口对象
window.title("定时关机程序")  # 设置窗口标题

# 设置窗口大小
window.geometry("500x300")  # 设置窗口宽度和高度

# 设置ttk主题
style = ttk.Style()  # 创建ttk样式对象
style.theme_use('clam')  # 使用clam主题

# 创建标签
label = ttk.Label(window, text="请输入关机时间(时:分:秒):")  # 创建标签对象
label.pack()  # 将标签放置到窗口中

# 创建时的填空
hour_frame = ttk.Frame(window)  # 创建Frame对象
hour_frame.pack()  # 将Frame放置到窗口中

hour_label = ttk.Label(hour_frame, text="时:")  # 创建标签对象
hour_label.pack(side=tk.LEFT)  # 将标签放置到Frame中

hour_entry = ttk.Entry(hour_frame)  # 创建Entry对象
hour_entry.pack(side=tk.LEFT)  # 将Entry放置到Frame中

# 创建分的填空
minute_frame = ttk.Frame(window)  # 创建Frame对象
minute_frame.pack()  # 将Frame放置到窗口中

minute_label = ttk.Label(minute_frame, text="分:")  # 创建标签对象
minute_label.pack(side=tk.LEFT)  # 将标签放置到Frame中

minute_entry = ttk.Entry(minute_frame)  # 创建Entry对象
minute_entry.pack(side=tk.LEFT)  # 将Entry放置到Frame中

# 创建秒的填空
second_frame = ttk.Frame(window)  # 创建Frame对象
second_frame.pack()  # 将Frame放置到窗口中

second_label = ttk.Label(second_frame, text="秒:")  # 创建标签对象
second_label.pack(side=tk.LEFT)  # 将标签放置到Frame中

second_entry = ttk.Entry(second_frame)  # 创建Entry对象
second_entry.pack(side=tk.LEFT)  # 将Entry放置到Frame中

# 创建按钮
button = ttk.Button(window, text="关机", command=shutdown)  # 创建按钮对象
button.pack()  # 将按钮放置到窗口中

# 运行窗口
window.mainloop()  # 进入窗口的主循环

程序运行结果: