Search code examples
python-3.xtkinterlogicttkttkwidgets

How to keep widgets when a new tab(ttk notebook) is created?


So I have a starter tab which has a textbox inside. I also want to create a new tab on the click of a button. When I create the new tab it does not show the textbox. I want all the tabs to have the same textbox and the same widgets.

Here is my code so far:

from tkinter import *
from tkinter import ttk

root = Tk()
root.geometry("600x600")

def newTab(*args): # How do I keep the textbox and other widgets in the new tabs
    newFrame = Frame(root, width=500, height=500)
    newFrame.pack()
    tabsArea.add(newFrame, text="Untitled.txt")

button = Button(root, command=newTab).pack()

# Tab Area --- First Tab 
tabsArea = ttk.Notebook(root)
tabsArea.pack(pady=15)

# Create Main Frame 
frame = Frame(root)
frame.pack(pady=5)

# Add Frame to Tab
tabsArea.add(frame, text="Untitled.txt")

# Textbox
textBox = Text(frame).pack()

root.mainloop()

How do I configure the text box and widgets in the newFrame/new tab?


Solution

  • You need to add a new text widget in each tab. Your code is just creating empty frames. Also, you shouldn't be calling newFrame.pack() since you are adding newFrame to the notebook.

    Here is a slimmed down version of your code that shows the basic concept:

    from tkinter import *
    from tkinter import ttk
    
    root = Tk()
    root.geometry("600x600")
    
    def newTab(*args): 
        newFrame = Frame(root, width=500, height=500)
        tabsArea.add(newFrame, text="Untitled.txt")
        text = Text(newFrame)
        text.pack(fill="both", expand=True)
    
    button = Button(root, text="New Tab", command=newTab)
    tabsArea = ttk.Notebook(root)
    
    button.pack(side="top")
    tabsArea.pack(pady=15, fill="both", expand=True)
    
    # Add the first tab
    newTab()
    
    root.mainloop()