Search code examples
pythontkintertabsstyles

Styling a Single Tkinter Notebook Tab


I would like to change the foreground text colour of one Notebook tab to be different from the rest of the tabs as defined by the style created below. As noted I would have expected to get a red font for Tab B, but I am not sure what to style to get this one tab styled. Can someone tell me please what attribute I should change? Thank you very much.

import tkinter as tk
import tkinter.ttk as ttk

root = tk.Tk()
root.geometry('%dx%d+0+0' %(200,200))
# Style  # /68485915/
style = ttk.Style()
style.theme_use("default")

# Notebook Style
style.configure('TNotebook', background='white')
style.configure('TNotebook.Tab', background='white', foreground='black')
style.map('TNotebook.Tab',background=[("selected",'green')])
style.configure('Red.TNotebook.Tab', foreground = 'red')

# Create Notebook and Frames
Book = ttk.Notebook(root)

aFrame = ttk.Frame(Book)

# I apply the Red tab style to this frame, but the tab does not change from the style created above
# I am not sure what the relationship between the frame and the tab which is part of the notebook
bFrame = ttk.Frame(Book, style='Red.TNotebook.Tab') #/18855943/

# Pack
aFrame.pack(fill = tk.BOTH, expand = True)
bFrame.pack(fill = tk.BOTH, expand = True)
Book.pack(fill = tk.BOTH, expand = True)

# Add Tabs
Book.add(aFrame, text = 'A')
Book.add(bFrame, text = 'B')

root.mainloop()

I looked at the following questions, but none seemed to answer my problem:


Solution

  • I would like to change the foreground text colour of one Notebook tab to be different from the rest of the tabs as defined by the style created below

    • Use yummy instead of default.
    • Add two constant for green and red.
    • Add style.theme_create
    • Use style.theme_use("yummy")
    • Comment it out style.configure

    Snippet modified your script:

    import tkinter as tk
    import tkinter.ttk as ttk
    
    root = tk.Tk()
    root.geometry('%dx%d+0+0' %(200,200))
    # Style  # 68485915
    style = ttk.Style()
     
    COLOR_GREEN = "#26d663"
    COLOR_RED = "#dd0202"
    
    style.theme_create("yummy", parent="alt", settings={
        "TNotebook": {"configure": {"tabmargins": [2, 5, 2, 0] } },
        "TNotebook.Tab": {
        "configure": {"padding": [5, 1], "background": COLOR_GREEN},
        "map":       {"background": [("selected", COLOR_RED)],
        "expand": [("selected", [1, 1, 1, 0])] } } } )
    
    style.theme_use("yummy")
    
     
    # Create Notebook and Frames
    Book = ttk.Notebook(root)
    
    aFrame = ttk.Frame(Book)
    Book.add(aFrame, text = 'A')
    bFrame = ttk.Frame(Book) #/18855943/
    Book.add(bFrame, text = 'B')
    Book.pack(fill = tk.BOTH, expand = True)
      
    
    root.mainloop()
    

    Screenshot:

    enter image description here