Dynamic night mode in addons

I’ve been using this code snippet in an addon to detect if night mode is on or not. It changes some colors if night mode is on. But it requires a restart each time for it to take affect. The rest of anki will get darker when night mode is triggered, but the addon will stay light until Anki is restarted. Is there a better way to implement night mode detection? Ideally one that does not require restarts

from aqt.theme import theme_manager

def isnightmode():
     return theme_manager.night_mode

if isnightmode():
    [night mode formatting]
else:
    [light mode formatting]

There is a theme_did_change hook.

2 Likes

I tried to implement the hook, but something still seems to be wrong. It still only updates the colors when Anki is restarted. Toggling night mode doesn’t do anything until I restart. I’m on macOS btw and am using the most recent stable Anki version.

from anki.hooks import addHook
from aqt.theme import theme_manager

# Global variables for colors
qtxt = "black"
qbg = "rgba(228, 228, 228, 1)" 
qfg = "#3399cc" 
qbr = 0 
qtr = 0 

def set_colors():
    global qtxt, qbg, qfg, qbr, qtr
    if theme_manager.night_mode:
        qtxt = "aliceblue"
        qbg = "rgba(39, 40, 40, 1)"
    else:
        qtxt = "black"
        qbg = "rgba(228, 228, 228, 1)"

# Initial setting of colors
set_colors()

addHook('theme_did_change', set_colors)

The hook should be used like this:

from aqt import gui_hooks

gui_hooks.theme_did_change.append(set_colors)

https://addon-docs.ankiweb.net/hooks-and-filters.html

3 Likes