Search code examples
pythonpython-3.xtkinterttkttkwidgets

How to expand ttk notebook label or tab button to fill window


enter image description here

I want to expand label to fill window

For example we use in tk button

parent.columnconfigure(0, weight=1)

button.grid(sticky='ew')

Can we do something like this to expand both label name to capture all available screen

And my second question : How to change background color or all available settings for that label or button tab

Thanks in advance

import tkinter as tk
from tkinter import ttk

root = tk.Tk()
root.geometry('600x400+0+0')
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)

tabs = ttk.Notebook()
tabs.grid(row=0, column=0, sticky='nsew')

tab1 = tk.Frame(tabs, bg='red')
tab2 = tk.Frame(tabs, bg='green')

tabs.add(tab1, text='First Tab')
tabs.add(tab2, text='Second Tab')

root.mainloop()


Solution

  • First question

    I used a style to configure the width of the tabs:

    style = ttk.Style(root)
    style.configure('TNotebook.Tab', width=1000)
    

    Because I set a very large width, the window is too small to display fully all the tabs, so they are shrunk to fit, which gives exactly the desired result. To ensure that the tab width is large enough, regardless of the screen used, one can use .winfo_screenwidth().

    Full example:

    import tkinter as tk
    from tkinter import ttk
    
    root = tk.Tk()
    root.geometry('600x400+0+0')
    root.columnconfigure(0, weight=1)
    root.rowconfigure(0, weight=1)
    
    style = ttk.Style(root)
    style.configure('TNotebook.Tab', width=root.winfo_screenwidth())
    
    tabs = ttk.Notebook()
    tabs.grid(row=0, column=0, sticky='nsew')
    
    tab1 = tk.Frame(tabs, bg='red')
    tab2 = tk.Frame(tabs, bg='green')
    tab3 = tk.Frame(tabs, bg='blue')
    
    tabs.add(tab1, text='First Tab')
    tabs.add(tab2, text='Second Tab')
    tabs.add(tab3, text='Third Tab')
    
    root.mainloop()
    

    screenshot

    Second question

    I am not exactly sure whether this is what was asked, but the settings of the tabs can be changed using a style. For instance, to set the background color:

    style.configure('TNotebook.Tab', background='green')
    

    The above code set to green the background of all unselected tabs. The background of the selected tab can be set with

    style.map('TNotebook.Tab', background=[('selected', 'yellow')])
    

    However it is not possible to change the background color of the tabs individually. To do that the only option is to code your own notebook widget using buttons or labels as tabs.