Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect OS dark mode in Python

I'm writing a small program in python with a GUI that I'm using tkinter for. What I'd like to do is add dark mode support to my program. Mac OS, Ubuntu (at least Gnome) and Windows 10 all have a system-wide setting for "dark mode" that'll make all programs automatically run with a dark theme.

But how do I check that settings (ideally, OS-independant) so my program knows if it needs to render light mode or dark mode? I found a bunch of libraries like darkdetect that'll handle this for MacOS, but I haven't found anything for Ubuntu and Windows 10.

I know that I can use stuff like ttkthemes to create a dark themed design for my program, but how do I know when to enable that? How can a python script running on Windows 10 or on Ubuntu 20.04 figure out if the user enabled the dark mode in the operating system settings?

Ideally I'm looking for a solution / code that'll work on all three operating systems, but if that's not possible (as I suspect) OS-dependant code would be fine as well. I just can't find proper examples for non-MacOS systems anywhere.

like image 861
Florian Bach Avatar asked Dec 14 '20 19:12

Florian Bach


People also ask

How do you detect if the OS is in dark mode in browsers?

CSS provides media queries to detect in Chrome and Firefox. prefers-color-scheme is a CSS media query to detect dark or light colors. As per mozilla, It supports all popular browsers. For webkit and safari browsers, you can use prefers-dark-interface media query.

How do you find dark mode preferences?

The prefers-color-scheme media query allows us to detect whether the system dark mode is enabled. It is a very useful feature that will allow us to change the colors of the page accordingly. This media query will return true if the system dark mode is enabled. It will return false if the user is using a light theme.


1 Answers

Quick answer for Windows 10

def detect_darkmode_in_windows(): 
    try:
        import winreg
    except ImportError:
        return False
    registry = winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER)
    reg_keypath = r'SOFTWARE\Microsoft\Windows\CurrentVersion\Themes\Personalize'
    try:
        reg_key = winreg.OpenKey(registry, reg_keypath)
    except FileNotFoundError:
        return False

    for i in range(1024):
        try:
            value_name, value, _ = winreg.EnumValue(reg_key, i)
            if value_name == 'AppsUseLightTheme':
                return value == 0
        except OSError:
            break
    return False
  • It checks if winreg can be imported, if not you are probably not using Windows
  • The relevant registry key is searched, if not found, it is assumed that dark mode is not enabled
  • If the registry key is present and the value is set to 0, dark mode is set
like image 52
Maximilian Peters Avatar answered Oct 16 '22 05:10

Maximilian Peters