Python Tkinter设置Azure主题后TTK按钮背景色无法修改
TTK Azure主题下按钮自定义背景颜色不生效的解决方法
Azure主题的TButton使用图片元素作为按钮背景,而非原生的颜色属性,因此直接通过configure设置background不会生效,但padding等布局属性不受影响——因为它们作用于按钮的布局容器而非背景元素。
以下是两种可行的解决方式:
方法一:自定义样式替换按钮元素
通过重新定义按钮的元素,使用TTK默认的颜色型按钮元素替代Azure主题的图片元素,之后即可正常设置背景色:
import tkinter as tk from tkinter import ttk def myfunc(): print("Button Clicked") root = tk.Tk() root.geometry("200x200") root.tk.call("source", "C:/Users/samue/OneDrive/Desktop/Website folder/Azure-ttk-theme-main/azure.tcl") root.tk.call("set_theme", "dark") buttonstyle = ttk.Style() # 从默认主题继承原生按钮元素(非图片类型) buttonstyle.element_create("custom.Button.button", "from", "default") # 为自定义样式配置布局,使用新的按钮元素 buttonstyle.layout("custom.TButton", [ ('custom.Button.button', {'sticky': 'nswe', 'children': [ ('Button.focus', {'sticky': 'nswe', 'children': [ ('Button.label', {'sticky': 'nswe'}) ]}) ]}) ]) # 配置背景色、前景色等属性 buttonstyle.configure("custom.TButton", padding=0, background="red", foreground="white") # 可选:设置不同交互状态下的颜色变化 buttonstyle.map("custom.TButton", background=[("active", "#cc0000"), ("pressed", "#990000")]) mybutton = ttk.Button(root, text="Click Me", command=myfunc, style="custom.TButton") mybutton.pack(pady=20) root.mainloop()
方法二:修改主题全局颜色变量(影响所有按钮)
如果希望所有按钮都使用红色背景,可以直接修改Azure主题的颜色变量,无需自定义样式:
import tkinter as tk from tkinter import ttk def myfunc(): print("Button Clicked") root = tk.Tk() root.geometry("200x200") root.tk.call("source", "C:/Users/samue/OneDrive/Desktop/Website folder/Azure-ttk-theme-main/azure.tcl") # 设置主题前修改对应颜色变量 root.tk.call("set", "::theme::azure::colors::button", "red") root.tk.call("set", "::theme::azure::colors::button-hover", "#cc0000") root.tk.call("set", "::theme::azure::colors::button-active", "#990000") root.tk.call("set_theme", "dark") mybutton = ttk.Button(root, text="Click Me", command=myfunc) mybutton.pack(pady=20) root.mainloop()
内容的提问来源于stack exchange,提问作者Samuel Crawford
相关产品推荐
相关产品推荐

