Skip to content

Instantly share code, notes, and snippets.

@DocMinus
Created February 13, 2021 11:59
Show Gist options
  • Save DocMinus/8119b9ddb4eeb7fafc84667ddd5479cc to your computer and use it in GitHub Desktop.
Save DocMinus/8119b9ddb4eeb7fafc84667ddd5479cc to your computer and use it in GitHub Desktop.
Prevent Windows from sleeping (i.e. keep system awake)
import tkinter as tk
import ctypes
import sys
class myBox(tk.Tk):
'''Prevents a Windows system from sleeping by keeping the screen alive.
At the same time an excercise in using tkinter....
(Python 3)
Inspired by multiple code snippets on the net, certainly the
SetThreadExecutionState gimmick.
'''
def __init__(self):
tk.Tk.__init__(self)
#self.root = tk.Tk()
self.geometry("200x100")
self.label = tk.Label(self, text="Default settings.")
self.label.pack(anchor='center')
self.title("Stop Screen & thus Windows from sleeping")
self.protocol("WM_DELETE_WINDOW", self.on_exit)
self.button1 = tk.Button(self,
text="Default",
fg="green",
command=self.display_off)
self.button1.pack(side='left', anchor='e', expand=True)
self.button2 = tk.Button(self,
text="Prevent Sleep",
fg="red",
command=self.display_on)
self.button2.pack(side='right', anchor='w', expand=True)
def on_exit(self):
self.display_off()
self.destroy()
def display_on(self):
ctypes.windll.kernel32.SetThreadExecutionState(0x80000002)
self.label['text'] = "PC always on!"
def display_off(self):
ctypes.windll.kernel32.SetThreadExecutionState(0x80000000)
self.label['text'] = "Default: sleep on."
if __name__ == "__main__":
myBox().mainloop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment