繁体   English   中英

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

[英]How do I execute a command after some time but with a cancel button

我想要的是让我的电脑在大约 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")

但如果我按下取消按钮,它就会停止,什么也不会发生

您可以使用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()  

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM