Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Tuple index out of range for Tkinter Notebook tab creation

I found a very elegant version of tab creation here : Tkinter Notebook create new tabs by clicking on a plus/+ tab like every web browser

Unfortunately, as I am trying this solution, I get an ‘IndexError: tuple index out of range’

Don’t make fun of me please, it’s my first post here, and I just started learned Python a few months ago 🙂

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This script is supposed to create a new tab based on a custom frame each time I click on the "+" tab, but the app window doesn’t appear, and instead I get this "IndexError"

import tkinter as tk
from tkinter import ttk

class MainWindow(tk.Tk):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        notebook = ttk.Notebook(self)
        notebook.bind("<<NotebookTabChanged>>", self.add_tab(notebook))

        notebook.grid(sticky="NSEW")

        frame = ttk.Frame(self)
        notebook.add(frame, text="+")

    def add_tab(event, notebook):
        if notebook.select() == notebook.tabs()[-1]:
            index = len(notebook.tabs())-1
            frame = CustomFrame(notebook)
            notebook.insert(index, frame, text=f"Frame {index +1}")
            notebook.select(index)
    
class CustomFrame(ttk.Frame):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

root = MainWindow()
root.mainloop()

>Solution :

Note that notebook.bind("<<NotebookTabChanged>>", self.add_tab(notebook)) will execute self.add_tab(notebook) immediately.

It should be

notebook.bind("<<NotebookTabChanged>>", lambda e: self.add_tab(notebook))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading