Search code examples
pythonpython-3.xtkinterttkttkwidgets

How do I create a new tab in a notebook widget in tkinter without replacing the previous tab?


So I have this program written in Python Tkinter, it has two frames on two different tabs. On the first there is a button, which should create a third tab with the same frame as the first tab. However, instead of doing that, its replacing the first frame. How do I fix this?

Here is my code so far:

# Imports
from tkinter import *
from tkinter import ttk



# Screen
root = Tk()
root.geometry("600x600")
root.title("Example")



# Create New Tab Function
def CreateANewTabFunc():
    TabControl.add(Frame1, text="Tab 3")


    
# Tab Control - Used for Placing the Tabs
TabControl = ttk.Notebook(root)
TabControl.pack()



# Frame 1 = Main Frame
Frame1 = Frame(TabControl, width=500, height=500, bg="Orange")
Frame1.pack()



# Frame 2 = Settings or Something Else
Frame2 = Frame(TabControl, width=500, height=500, bg="Green")
Frame2.pack()



TabControl.add(Frame1, text="Tab 1")
TabControl.add(Frame2, text="Tab 2")



ExampleButton = Button(Frame1, text="Click Here to Add New Tab to notebook", command=CreateANewTabFunc)
ExampleButton.pack()



# Mainloop
root.mainloop()

Solution

  • You can't use the same frame on two tabs. If you want to create a third tab, you need to create a third frame.

    def CreateANewTabFunc():
        another_frame = Frame(TabControl, bg="pink")
        TabControl.add(another_frame, text="Tab 3")