Select Tabs in Tkinter Notebook: Navigating with Ease

In this tutorial, we’ll learn how to select tabs in Tkinter notebook, including selecting tabs by index, tab id, widget reference, detecting when a tab is selected, and implementing next/previous tab navigation.

Also, we’ll learn how to persist the tab selection state.

 

 

Select a Tab by Index

You can pass the index of the tab to the select_tab function to select tabs by index:

import tkinter as tk
from tkinter import ttk
root = tk.Tk()
root.title("Sample Data Analysis")
notebook = ttk.Notebook(root)
notebook.pack(fill='both', expand=True)
data_tab = ttk.Frame(notebook)
settings_tab = ttk.Frame(notebook)
notebook.add(data_tab, text='Data')
notebook.add(settings_tab, text='Settings')
def select_tab(index):
    notebook.select(index)
select_tab(0)
root.mainloop()

 

Select a Tab by Tab ID

You can select tabs using the select_tab function by passing the tab ID:

import tkinter as tk
from tkinter import ttk
root = tk.Tk()
root.title("Data Dashboard")
notebook = ttk.Notebook(root)
user_data_tab = ttk.Frame(notebook)
call_records_tab = ttk.Frame(notebook)
network_stats_tab = ttk.Frame(notebook)
notebook.add(user_data_tab, text='User Data')
notebook.add(call_records_tab, text='Call Records')
notebook.add(network_stats_tab, text='Network Stats')
notebook.pack(expand=True, fill='both')
def select_tab(tab_id):
    notebook.select(tab_id)
select_tab(network_stats_tab)
root.mainloop()

 

Select a Tab by Widget Reference

You can select tabs using select function by passing the widget reference to it:

import tkinter as tk
from tkinter import ttk
root = tk.Tk()
root.title("Data Analysis")
notebook = ttk.Notebook(root)
notebook.pack(fill='both', expand=True)
tab1 = ttk.Frame(notebook)
tab2 = ttk.Frame(notebook)
tab3 = ttk.Frame(notebook)
notebook.add(tab1, text='Tab 1: User Data')
notebook.add(tab2, text='Tab 2: Usage Patterns')
notebook.add(tab3, text='Tab 3: Network Statistics')
notebook.select(tab2)
root.mainloop()

 

Get Currently Selected Tab

We’ll create a function to display the title of the currently selected tab or a message if no tab is selected.

import tkinter as tk
from tkinter import ttk
def current_tab_info():
    try:
        selected_tab = notebook.index(notebook.select())
        tab_text = notebook.tab(selected_tab, "text")
        print(f"Currently selected tab: {tab_text}")
    except tk.TclError:
        print("No tab is currently selected.")
root = tk.Tk()
root.title("Data Dashboard")
notebook = ttk.Notebook(root)
notebook.pack(fill='both', expand=True)
tab1 = ttk.Frame(notebook)
tab2 = ttk.Frame(notebook)
notebook.add(tab1, text='Tab 1: User Insights')
notebook.add(tab2, text='Tab 2: Service Analytics')
current_tab_info()
root.mainloop()

Output:

Currently selected tab: Tab 1: User Insights

 

Detect When a Tab is Selected

You can trigger specific actions or updates whenever the user navigates to a different tab.

Let’s create a function that prints the title of the newly selected tab.

import tkinter as tk
from tkinter import ttk
def on_tab_selected(event):
    selected_tab = event.widget.index("current")
    tab_title = event.widget.tab(selected_tab, "text")
    print(f"Tab selected: {tab_title}")
root = tk.Tk()
root.title("Data Dashboard")
notebook = ttk.Notebook(root)
notebook.pack(fill='both', expand=True)
tab1 = ttk.Frame(notebook)
tab2 = ttk.Frame(notebook)
tab3 = ttk.Frame(notebook)
notebook.add(tab1, text='Tab 1: Subscriber Details')
notebook.add(tab2, text='Tab 2: Usage Statistics')
notebook.add(tab3, text='Tab 3: Network Performance')

# Bind the select event
notebook.bind("<<NotebookTabChanged>>", on_tab_selected)
root.mainloop()

When a new tab is selected, the <<NotebookTabChanged>> event occurs, and the on_tab_selected function is called.

 

Implement Next/Previous Tab Selection Functionality

We’ll create two functions, select_next_tab and select_previous_tab, and bind them to buttons for user interaction.

These functions will calculate the index of the next or previous tab and select it accordingly.

import tkinter as tk
from tkinter import ttk

def select_next_tab():
    current_tab = notebook.index(notebook.select())
    next_tab = (current_tab + 1) % notebook.index("end")
    notebook.select(next_tab)

def select_previous_tab():
    current_tab = notebook.index(notebook.select())
    previous_tab = (current_tab - 1) % notebook.index("end")
    notebook.select(previous_tab)
root = tk.Tk()
root.title("Data Navigation")
notebook = ttk.Notebook(root)
notebook.pack(fill='both', expand=True)
tab1, tab2, tab3 = ttk.Frame(notebook), ttk.Frame(notebook), ttk.Frame(notebook)
notebook.add(tab1, text='Tab 1: Customer Data')
notebook.add(tab2, text='Tab 2: Traffic Analysis')
notebook.add(tab3, text='Tab 3: Revenue Insights')
prev_button = ttk.Button(root, text="Previous", command=select_previous_tab)
prev_button.pack(side='left')
next_button = ttk.Button(root, text="Next", command=select_next_tab)
next_button.pack(side='right')
root.mainloop()

The select_next_tab and select_previous_tab functions calculate the index of the next or previous tab.

 

Save and Restore Tab Selection State

You can save the index of the currently selected tab to a file upon closing the application and read this index to restore the tab state when the application is launched again.

import tkinter as tk
from tkinter import ttk
def on_closing():
    with open('tab_state.txt', 'w') as file:
        current_tab = notebook.index(notebook.select())
        file.write(str(current_tab))
    root.destroy()
def restore_tab_state():
    try:
        with open('tab_state.txt', 'r') as file:
            saved_tab = int(file.read())
            notebook.select(saved_tab)
    except (FileNotFoundError, ValueError):
        pass
root = tk.Tk()
root.title("Data Persistence")
notebook = ttk.Notebook(root)
notebook.pack(fill='both', expand=True)
tab1, tab2, tab3 = ttk.Frame(notebook), ttk.Frame(notebook), ttk.Frame(notebook)
notebook.add(tab1, text='Tab 1: Service Quality')
notebook.add(tab2, text='Tab 2: Customer Feedback')
notebook.add(tab3, text='Tab 3: Operational Metrics')
restore_tab_state()
root.protocol("WM_DELETE_WINDOW", on_closing)
root.mainloop()

The tab selection state is stored in tab_state.txt.

The on_closing function saves the index of the current tab to a file when the application is closed, enabling state persistence.

The restore_tab_state function reads this index from the file when the application starts and selects the corresponding tab.

Leave a Reply

Your email address will not be published. Required fields are marked *