在 Python 中检测 OS 暗模式

Flo*_*ach 7 python user-interface tkinter

我正在用 python 编写一个带有 GUI 的小程序,我正在使用 tkinter。我想做的是为我的程序添加暗模式支持。Mac OS、Ubuntu(至少是 Gnome)和 Windows 10 都有一个系统范围的“黑暗模式”设置,这将使所有程序自动以黑暗主题运行。

但是我如何检查这些设置(理想情况下,与操作系统无关),以便我的程序知道它是否需要渲染亮模式或暗模式?我找到了一堆像darkdetect这样的库,它们可以为 MacOS 处理这个问题,但我没有找到任何适用于 Ubuntu 和 Windows 10 的库。

我知道我可以使用 ttkthemes 之类的东西为我的程序创建一个黑暗主题的设计,但我怎么知道何时启用它?在 Windows 10 或 Ubuntu 20.04 上运行的 python 脚本如何确定用户是否在操作系统设置中启用了暗模式?

理想情况下,我正在寻找可以在所有三个操作系统上运行的解决方案/代码,但如果这不可能(正如我怀疑的那样),依赖于操作系统的代码也可以。我在任何地方都找不到非 MacOS 系统的正确示例。

Max*_*ers 10

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
Run Code Online (Sandbox Code Playgroud)
  • 它检查是否winreg可以导入,如果不能导入,您可能没有使用 Windows
  • 搜索相关注册表项,如果没有找到,则认为没有启用深色模式
  • 如果该注册表项存在且值设置为 0,则设置暗模式


Saa*_*aad 7

在 macOS 上,暗/亮模式位于外观下,可以通过defaults read -g AppleInterfaceStyle在终端上运行简单的命令来检查。

  • 在黑暗模式下,命令返回

    Dark
    
    Run Code Online (Sandbox Code Playgroud)

    它只会返回存在的Dark意义AppleInterfaceStyle

  • 在 Light 模式下,相同的命令返回

    2020-12-18 17:44:21.870 defaults[20253:5665627] 
    The domain/default pair of (kCFPreferencesAnyApplication, AppleInterfaceStyle) does not exist
    
    Run Code Online (Sandbox Code Playgroud)

    默认情况下,灯光模式已启用,因此AppleInterfaceStyle不存在,这就是它返回错误的原因。


我们可以简单地创建一个函数,如果启用了深色模式并且启用了浅色模式,该函数将返回TrueFalse

import subprocess

def check_appearance():
    """Checks DARK/LIGHT mode of macos."""
    cmd = 'defaults read -g AppleInterfaceStyle'
    p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE, shell=True)
    return bool(p.communicate()[0])

Run Code Online (Sandbox Code Playgroud)

  • 问题不是关于非 Mac 操作系统吗? (3认同)

Vot*_*fee 5

我本来打算创建自己的通用函数,但看起来有人已经为所有操作系统制作了一个不错的包: https: //pypi.org/project/darkdetect/

import darkdetect

darkdetect.theme()
# Returns 'Dark'

darkdetect.isDark()
# Returns True

darkdetect.isLight()
# Returns False
Run Code Online (Sandbox Code Playgroud)