如何在一段时间后执行命令但使用取消按钮

时间:2016-05-14 11:52:32

标签: python tkinter sleep sleep-mode

我想要的是让我的电脑在大约10秒后睡眠,但我希望它有一条带有取消按钮的消息

这是我试过的:

这是我对tkinter的警告:

from tkinter import *
import ctypes

def callback():
quit()


root = Tk()
root.geometry("400x268")
root.title("Alert")
root.configure(background='light blue')



label = Label(root, text="ALERT this device will go to sleep soon!",   fg="red")
label.config(font=("Courier", 12))
label.configure(background='light blue')
quitButton = Button(root, text="do not sleep!", command=callback)
quitButton.pack()
quitButton.place(x=150, y=150)


label.pack()
root.mainloop()  

我需要它倒数到睡觉(这个命令):

import time
import os

os.system("Powercfg -H OFF")
os.system("rundll32.exe powrprof.dll,SetSuspendState 0,1,0")

但如果按下取消按钮,它将停止,不会发生任何事情

1 个答案:

答案 0 :(得分:0)

您可以使用after方法。 after(DELAY_MS, CALLBACK=None, *args)。 像这样:

from tkinter import *
import ctypes, os

def callback():
    active.set(False)
    #root.destroy()         # Uncoment this to close the window

def sleep():
    if not active.get(): return
    root.after(1000, sleep)
    timeLeft.set(timeLeft.get()-1)
    timeOutLabel['text'] = "Time Left: " + str(timeLeft.get())  #Update the label
    if timeLeft.get() == 0:                                     #sleep if timeLeft = 0
        os.system("Powercfg -H OFF")
        os.system("rundll32.exe powrprof.dll,SetSuspendState 0,1,0")
        callback()

root = Tk()
root.geometry("400x268")
root.title("Alert")
root.configure(background='light blue')

timeLeft = IntVar()
timeLeft.set(10)            # Time in seconds until shutdown

active = BooleanVar()
active.set(True)            # Something to show us that countdown is still going.

label = Label(root, text="ALERT this device will go to sleep soon!",   fg="red")
label.config(font=("Courier", 12))
label.configure(background='light blue')
label.pack()
timeOutLabel = Label(root, text = 'Time left: ' + str(timeLeft.get()), background='light blue') # Label to show how much time we have left.
timeOutLabel.pack()
quitButton = Button(root, text="do not sleep!", command=callback)
quitButton.pack()   
quitButton.place(x=150, y=150)      

root.after(0, sleep)
root.mainloop()