电脑定时关机python代码

#coding=utf-8
'''
    该程序是定时关机软件,输入指定时间就关电脑
'''
import os
import time
import threading
from datetime import timedelta, datetime
from tkinter import *
from tkinter import messagebox

class Application(Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.pack()
        self.createWidget()

    def createWidget(self):
        ''' 创建登录界面'''
        Label(self, text="时(H):").grid(row=0, column=0)
        self.entry01 = Entry(self, textvariable=StringVar())
        self.entry01.grid(row=0, column=1)
        Label(self, text="点  (注:输入0-23之间数字)").grid(row=0, column=2)

        Label(self, text="分(M):").grid(row=1, column=0)
        self.entry02 = Entry(self, textvariable=StringVar())
        self.entry02.grid(row=1, column=1)
        Label(self, text="分  (注:输入0-59之间数字)").grid(row=1, column=2)

        Button(self, text="确定", command=self.shutdown_time).grid(row=2, column=1,sticky=W)
        Button(self, text="取消", command=self.cancel_shutdown).grid(row=2, column=1,sticky=E)

    def shutdown_time(self):
        try:
            hour = int(self.entry01.get())
            minute = int(self.entry02.get())
            if not (0 <= hour <= 23 and 0 <= minute <= 59):
                raise ValueError

            now = datetime.now()
            shutdown_time = now.replace(hour=hour, minute=minute, second=0, microsecond=0)

            # 判断关闭时间是否小于现在的时间
            if shutdown_time < now:
                shutdown_time += timedelta(days=1)

            wait_time = (shutdown_time - now).total_seconds()

            # 使用线程来处理等待时间
            threading.Thread(target=self.wait_and_shutdown, args=(wait_time,)).start()
            messagebox.showinfo("小新提醒您:", f"电脑将于 {shutdown_time.strftime('%Y-%m-%d %H:%M:%S')} 关机")
        except ValueError:
            messagebox.showerror("错误", "请输入有效的时间")

    def wait_and_shutdown(self, wait_time):
        time.sleep(wait_time)
        os.system("shutdown /s /t 1")

    def cancel_shutdown(self):
        self.master.destroy()

if __name__ == "__main__":
    root = Tk()
    root.geometry("500x300+200+200")
    root.title("定时关机 V1.0版")
    app = Application(master=root)
    root.mainloop()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值