是否可以根据Windows 10当前的明暗主题配置更改tkinter应用程序的主题?

时间:2019-09-27 08:03:49

标签: python tkinter windows-10

当用户将Windows 10颜色应用程序模式从“浅”更改为“暗”时,如何使tkinter应用程序能够将其配色方案自动更改为暗色?

1 个答案:

答案 0 :(得分:1)

您可以使用root.after检查注册表中的更改。

from winreg import *
import tkinter as tk

root = tk.Tk()
root.config(background="white")
label = tk.Label(root,text="Light mode on")
label.pack()

def monitor_changes():
    registry = ConnectRegistry(None, HKEY_CURRENT_USER)
    key = OpenKey(registry, r'SOFTWARE\Microsoft\Windows\CurrentVersion\Themes\Personalize')
    mode = QueryValueEx(key, "AppsUseLightTheme")
    root.config(bg="white" if mode[0] else "black")
    label.config(text="Light Mode on" if mode[0] else "Dark Mode on",
                 bg="white" if mode[0] else "black",
                 fg="black" if mode[0] else "white")
    root.after(100,monitor_changes)

monitor_changes()

root.mainloop()

为完整起见,以下是配置ttk.Style对象以更改主题的方法:

root = tk.Tk()
style = ttk.Style()
style.configure("BW.TLabel",foreground="black",background="white")
label = ttk.Label(root,text="Something",style="BW.TLabel")
label.pack()

def monitor_changes():
    ...
    style.configure("BW.TLabel",foreground="black" if mode[0] else "white", background="white" if mode[0] else "black")
    ...