如何为Python Tkinter程序自定义Windows 11标题栏颜色?
在Windows 11下给Tkinter程序自定义标题栏颜色
一、原生Tkinter的局限
原生Tkinter不支持直接修改系统标题栏的颜色,默认只能沿用系统主题样式,或者隐藏原生标题栏后自行绘制(但需手动实现拖拽、窗口控制按钮等功能,成本较高)。
二、可行解决方案
1. 使用第三方库CustomTkinter
CustomTkinter是针对Tkinter的现代化扩展库,原生支持自定义标题栏颜色,适配Windows 11:
- 安装库:
pip install customtkinter
- 示例代码:
import customtkinter as ctk # 设置全局外观模式与默认主题 ctk.set_appearance_mode("dark") ctk.set_default_color_theme("blue") app = ctk.CTk() app.title("自定义标题栏演示") app.geometry("600x400") # 自定义标题栏颜色(浅色/深色模式分别设置) app.configure(fg_color=("#2C3E50", "#1A252F")) app.mainloop()
若需精细控制标题栏按钮颜色,可通过修改CTk组件样式或配置CTkToplevel的标题栏属性实现。
2. 调用Windows API(ctypes实现)
通过ctypes调用Windows DWM(桌面窗口管理器)API,直接修改原生Tkinter窗口的标题栏颜色,仅支持Windows 10 1809及以上版本(含Windows 11):
- 示例代码:
import tkinter as tk import ctypes # 定义Windows API常量与函数 DWMWA_CAPTION_COLOR = 35 DWMWA_ACCENT_COLOR = 36 user32 = ctypes.WinDLL('user32') dwmapi = ctypes.WinDLL('dwmapi') def set_titlebar_color(window, hex_color): # 获取窗口句柄 hwnd = user32.GetParent(window.winfo_id()) # 转换十六进制颜色为RGB数值 rgb_value = int(hex_color.lstrip('#'), 16) # 设置标题栏背景色 dwmapi.DwmSetWindowAttribute(hwnd, DWMWA_CAPTION_COLOR, ctypes.byref(ctypes.c_uint(rgb_value)), ctypes.sizeof(ctypes.c_uint(rgb_value))) # 设置标题栏按钮高亮色(可选) dwmapi.DwmSetWindowAttribute(hwnd, DWMWA_ACCENT_COLOR, ctypes.byref(ctypes.c_uint(rgb_value)), ctypes.sizeof(ctypes.c_uint(rgb_value))) root = tk.Tk() root.title("API自定义标题栏") root.geometry("600x400") # 设置标题栏为深蓝色 set_titlebar_color(root, "#2C3E50") root.mainloop()
三、PyInstaller打包后的修改说明
打包完成后无法直接修改已编译程序的标题栏颜色,必须在打包前通过代码实现自定义标题栏逻辑,再进行打包:
- 若使用CustomTkinter,打包时需确保PyInstaller正确收集库资源,推荐命令:
pyinstaller --onefile --windowed --add-data "path/to/customtkinter;customtkinter" your_script.py
或通过.spec文件配置资源路径,避免运行时丢失主题文件。
- 若使用ctypes调用Windows API,无需额外配置,直接打包即可(依赖系统自带DLL)。
四、额外提示
如果需要完全自定义标题栏的按钮样式、布局,可以隐藏原生标题栏(root.overrideredirect(True)),再用Tkinter组件手动绘制标题栏,同时绑定事件实现窗口拖拽、最小化/最大化/关闭功能,这种方式灵活性最高,但需处理更多细节逻辑。
内容的提问来源于stack exchange,提问作者nullcore3
相关产品推荐
相关产品推荐

