从 python 检测 macOS 中的暗模式

Detect dark mode in macos from python

我正在编写一个 PyQt 应用程序,我必须添加一个补丁,以便字体在启用暗模式的 macos 上可读:

app = QApplication([])
# Fix for the font colours on macos when running dark mode
if sys.platform == 'darwin':
    p = app.palette()
    p.setColor(QPalette.Base, QColor(101, 101, 101))
    p.setColor(QPalette.ButtonText, QColor(231, 231, 231))
    app.setPalette(p)
main_window = MainWindow()
main_window.show()
app.exec_()

此补丁的问题在于,它会导致在 macOS 上使用轻模式无法读取内容。

有没有一种方法可以从 python 或通过子进程使用标准 shell 命令检测 macOS 上的暗模式?

编辑: 从 PyQt 5.12 开始,不再需要暗模式修复。

基于 this question,您可以安装 pyobjc 并使用 NSUserDefaults:

>>> from Foundation import NSUserDefaults
>>> NSUserDefaults.standardUserDefaults().stringForKey_('AppleInterfaceStyle')
'Dark'

如果您不想导入 pyobjc,您可以使用 Darkdetect,一个只使用标准 Python 发行版提供的依赖项的专用包。

用法:

import darkdetect

>>> darkdetect.theme()
'Dark'

>>> darkdetect.isDark()
True

>>> darkdetect.isLight()
False

Darkdetect 也可以在 PyPI 上使用:pip install darkdetect

免责声明:我是 Darkdetect 的作者。