Home Python Course Menu Book

Python TKinter Form Tabs

 

Tabs are called Notebooks in the Tkinter ttk library. The idea is that you set up a parent Notebook and then add tabs to that Notebook.

In yiour code from the previous lesson, add the following line just after your geometry line and before mainloop:

tab_parent = ttk.Notebook(form)

In between the round brackets of Notebook, you need the name of a widget that the notebook is going on. For us, that's the main form. Our Notebook object is being held in a variable we've called tab_parent.

To set up a tab for your notebook, you create Form objects with the name of a Notebook between round brackets. Add these two lines:

tab1 = ttk.Frame(tab_parent)
tab2 = ttk.Frame(tab_parent)

This sets up two tab objects called tab1 and tab2. We now need to add them to the tab parent:

tab_parent.add(tab1, text="All Records")
tab_parent.add(tab2, text="Add New Record")

We're now using the add method of tab_parent. In between the round rackets of add, you need the name of the tab object you want to add. After a comma, we've added some text for the tab.

Finally, you need to pack the tab parent and its tabs:

tab_parent.pack(expand=1, fill='both')

The expand and fill option between pack ensure that the tabs fill the entire form. Your code should look like this:

Python code to set up two Tkinter Notebook tabs

Run your program again. You should now find that your form looks like this:

A Tkinter form with two tabs

You can click your Add New Record tab to activate it. You won't see much difference as we haven't added any widgets to them. Let's do that now.