简体   繁体   中英

How do I change the screen brightness in windows using python?

How do I change the screen brightness in windows using python, without using any extra python packages? I'd also like a way of getting what the screen brightness is currently at. I'm thinking that will need to be by using ctypes, but I can't find any information on how to do it.

It annoys me the way the screen brightness buttons on windows adjust the screen brightness in very large increments, so I made a python tkinter program to display the current screen brightness on the taskbar and when I scroll the mouse wheel on the tkinter window it changes the screen brightness:

import subprocess
from tkinter import Canvas, Tk

win = Tk()
win.overrideredirect(True)

canvas = Canvas(win, bg = "#101010", highlightthickness = 0)
canvas.pack(fill = "both", expand = True)

def trim(string, l = None, r = None, include = False, flip = False):
    string = str(string)
    if l and l in string:
        string = string[(string.rindex(l) if flip else string.index(l)) + (0 if include else len(l)):]
    if r and r in string:
        string = string[:(string.index(r) if flip else string.rindex(r)) + (len(r) if include else 0)]
    return string

def set_screen_brightness():
    subprocess.run(
        ["powershell",
         f"(Get-WmiObject -Namespace root/WMI -Class WmiMonitorBrightnessMethods).WmiSetBrightness(1,{current_brightness})"],
        stdout = subprocess.PIPE, stderr = subprocess.STDOUT, shell = True)

def get_screen_brightness():
    value = subprocess.check_output(
        ["powershell", f"Get-Ciminstance -Namespace root/WMI -ClassName WmiMonitorBrightness"],
        shell = True)
    return int(trim(value, l = "CurrentBrightness : ", r = r"\r\nInstanceName      : "))

current_brightness = get_screen_brightness()

brightness_text = canvas.create_text(30, 25, text = current_brightness,
                                         font = ("Segue ui", 14, "bold"), fill = "White", anchor = "w")

sw, sh = win.winfo_screenwidth(), win.winfo_screenheight()
win.geometry(f"69x50+{sw - 505}+{sh - 49}")

def mouse_wheel_screen_brightness(scroll):
    global current_brightness, mouse_wheel_screen_brightness_wa
    if "mouse_wheel_screen_brightness_wa" in globals():
        win.after_cancel(mouse_wheel_screen_brightness_wa)

    current_brightness += 2 if scroll else -2
    if current_brightness < 0: current_brightness = 0
    if current_brightness > 100: current_brightness = 100
    canvas.itemconfig(brightness_text, text = current_brightness)

    mouse_wheel_screen_brightness_wa = win.after(100, lambda: set_screen_brightness())

win.bind("<MouseWheel>", lambda e: mouse_wheel_screen_brightness(e.delta > 0))

def topmost():
    win.attributes("-topmost", True)
    win.after(100, topmost)
topmost()

win.mainloop()

I'm sure there must be a fast way of changing the screen brightness in ctypes, without any extra python packages. With using a subprocess call to Powershell the screen brightness text keeps freezing. I want to do it without using any extra python packages because when I try to install a python package it says that there was a problem confirming the ssl certificate. I googled it and tried to fix it, but I can't get it to work.

by the help of PowerShell commands we can easily increase or decrease the brightness of windows without any external packages

WmiSetBrightness(1,<brightness % goes here>)

import subprocess

subprocess.run(["powershell", "(Get-WmiObject -Namespace root/WMI -Class WmiMonitorBrightnessMethods).WmiSetBrightness(1,40)"])

the subprocess is the internal library that comes with python.

just run the above code, hope this will work.

The another way to do it without any library is:

import subprocess


def run(cmd):
    completed = subprocess.run(["powershell", "-Command", cmd], capture_output=True)
    return completed

if __name__ == '__main__':
    take_brightness = input("Please enter the brightness level: ")
    command = "(Get-WmiObject -Namespace root/WMI -Class WmiMonitorBrightnessMethods).WmiSetBrightness(1," + take_brightness + ")"
    hello_command = f"Write-Host {command}"
    hello_info = run(hello_command)

Install screen brightness control using pip Windows: pip install screen-brightness-control

Mac/Linux: pip3 install screen-brightness-control I guess

Then use this code

import screen_brightness_control as sbc

sbc.set_brightness(25) # Number will be any number between 0 and hundred
# Sets screen brightness to 25%

I found info on the screen brightness module here

I used the WMI library and it really worked fine. Here is the code, but this is for Windows. I think it is OS specific so if it doesn't work for you, you should look for a better solution.

import wmi
    
brightness = 40 # percentage [0-100] For changing thee screen 
c = wmi.WMI(namespace='wmi')
methods = c.WmiMonitorBrightnessMethods()[0]    
methods.WmiSetBrightness(brightness, 0)

Please upvote and accept the answer if you like it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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