You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为ttk.Notebook的每个标签页设置不同背景色?

解决ttk Notebook多页面背景色独立设置的问题

问题出在你直接修改了全局的TFrame样式——ttk的Style是全局共享的,后初始化的SubFrame把TFrame改成蓝色,会覆盖之前MainFrame设置的红色,导致所有页面都用最后一次的样式。

要实现不同页面不同背景色,得给每个页面的Frame创建独立的自定义样式,具体修改如下:

  1. 给每个Frame子类创建专属的样式名(比如Main.TFrame、Sub.TFrame),不要修改全局的TFrame
  2. 初始化Frame时指定使用对应的自定义样式
  3. 给页面内的ttk.Label也配置对应样式,让标签背景和页面背景一致

修改后的完整代码:

import tkinter as tk
from tkinter import ttk


class MainFrame(ttk.Frame):
    def __init__(self, container):
        # 初始化时指定使用自定义样式
        super().__init__(container, style='Main.TFrame')
        
        s = ttk.Style()
        # 创建Main.TFrame样式,设置红色背景
        s.configure('Main.TFrame', background='red')
        # 同步设置对应Label的样式,让标签背景和Frame一致
        s.configure('Main.TLabel', background='red')

        self.labelA = ttk.Label(self, text="This is on MainFrame", style='Main.TLabel')
        self.labelA.grid(column=1, row=2, padx=30, pady=30)

        self.buttonA = tk.Button(self, text="R 1")
        self.buttonA.grid(column=1, row=3)
        

class SubFrame(ttk.Frame):
    def __init__(self, container):
        super().__init__(container, style='Sub.TFrame')
        
        s = ttk.Style()
        s.configure('Sub.TFrame', background='blue')
        s.configure('Sub.TLabel', background='blue')

        self.labelB = ttk.Label(self, text="This is on SubFrame", style='Sub.TLabel')
        self.labelB.grid(column=1, row=2, padx=30, pady=30)

        self.buttonB = tk.Button(self, text="R 1")
        self.buttonB.grid(column=1, row=3)


class App(tk.Tk):
    def __init__(self):
        super().__init__()

        s = ttk.Style()

        unfocus = "gray"
        focus = "#F2C84B"

        s.theme_create( "custom", parent="alt", settings={
            "TNotebook": {"configure": {"tabmargins": [2, 5, 2, 0] } },
            "TNotebook.Tab": {
                "configure": {"padding": [5, 1], "background": unfocus },
                "map":       {"background": [("selected", focus)],
                          "expand": [("selected", [1, 1, 1, 0])] } } } )

        s.theme_use("custom")

        self.notebook = ttk.Notebook(self)

        self.Frame1 = MainFrame(self.notebook)
        self.Frame2 = SubFrame(self.notebook)

        self.notebook.add(self.Frame1, text='MainFrame')
        self.notebook.add(self.Frame2, text='SubFrame')

        self.notebook.pack(expand=1, fill="both")

        self.geometry('800x500')
        self.title("TABS")
           

if __name__ == '__main__':
    app = App()
    app.mainloop()

这样修改后,两个页面就会分别显示红色和蓝色背景,且内部标签的背景也会和页面匹配。

内容的提问来源于stack exchange,提问作者bob_the_bob

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 18:53:10